// ==UserScript==
// @name            网易BUFF价格比例(找挂刀)插件
// @icon            https://s1.ax1x.com/2022/03/25/qt3mcj.png
// @description     找挂刀，看比例，挑玄学
// @version         3.0.0
// @note            更新于 2020年10月10日 10:10:10
// @author          Pronax
// @homepageURL     https://greasyfork.org/zh-CN/users/412840-newell-gabe-l
// @license         AGPL-3.0
// @copyright       2021, Pronax
// @include         /https:\/\/buff\.163\.com\/(market|goods)\/(csgo|dota2|rust|h1z1|tf2|pubg|pubg_recycle|\d+)/
// @run-at          document-body
// @grant           GM_info
// @grant           GM_addStyle
// @grant           GM_setValue
// @grant           GM_getValue
// @grant           GM_xmlhttpRequest
// @grant           GM_registerMenuCommand
// @require         https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery-toast-plugin/1.3.2/jquery.toast.min.js
// @connect         steamcommunity.com
// @connect         store.steampowered.com
// @connect         buffyouhou.web3v.vip
// @namespace       https://greasyfork.org/zh-CN/users/412840-newell-gabe-l
// ==/UserScript==


(function () {
    // 本插件基于 steam买 buff卖 为基础
    'use strict';

    // 原脚本的代码，封装为异步函数，方便在内部使用 await
    (async function youhou_task1() {
        'use strict';

        // 防止重复安装冲突
        if ($(".logo").hasClass("buffHelperLoaded")) { return; }
        $(".logo").addClass("buffHelperLoaded");

        // 作用于 info函数 用于输出debug信息
        var debugflag = true;
        debugflag = false;

        // 全局（插件环境）异常捕获
        window.onerror = function (e) {
            try {
                // e.returnValue = false;     // 值为false时不会触发console.error事件
                if (!e.error) { return; }     // 通常是浏览器内各种原因导致的报错
                let scriptName = undefined;
                // let errorType = undefined;   也许可以用来区分scriptManager，但是现在用不上
                let renderingEngine = window.navigator.userAgent.match(/(Chrome|Firefox)\/([^ ]*)/);
                let lineno = e.lineno;
                switch (renderingEngine && renderingEngine[1]) {
                    case "Chrome":
                        // chrome+TamperMonkey在这个脚本内报错的情况下会需要两次decode
                        scriptName = decodeURIComponent(decodeURIComponent(e.filename.match(/([^\/=]*)\.user\.js/)[1]));
                        lineno -= 534;
                        // errorType = e.message.match(/^Uncaught ([a-zA-Z]*): /)[1];
                        break;
                    case "Firefox":
                        scriptName = decodeURIComponent(e.error.stack.match(/\/([^\/]*)\.user\.js/)[1]).trim();
                        lineno -= 1;
                        // errorType = e.message.match(/^([a-zA-Z]*): /)[1];
                        break;
                    default:
                        return;
                }
                if (scriptName == "网易BUFF价格比例(找挂刀)插件") {
                    let colno = e.colno;
                    let errorMsg = e.error.message;
                    let msgBody = `内核：${renderingEngine[0]}<br/>版本：${GM_info.script.version}<br/>区域：${helper_config.steamCurrency} ${steamConnection ? 200 : steamConnection == undefined ? "Unknow" : 404}<br/>位置：${lineno}:${colno}<br/>信息：${errorMsg}<br/>路径：${location.pathname}<br/>哈希：${location.hash}`;
                    let msgHtml = `恭喜！你可能发现了一个bug<hr/>${msgBody}<hr/>点击下面的链接可以直接进行反馈<br/><a href='mailto:funkyturkey@yeah.net?subject=【${GM_info.script.version}】${lineno}:${colno} ${errorMsg}&body=${encodeURIComponent(msgBody.replaceAll("<br/>", "\r\n"))}'>邮件反馈</a><a href="https://greasyfork.org/zh-CN/scripts/410137/feedback#post-discussion" target="_blank">反馈贴反馈</a>`;
                    showMessage("出现了意料之外的错误", msgHtml, "error", false);
                } else {
                    console.log(`插件名称：${scriptName}\n代码位置：${e.lineno}:${e.colno}\n错误信息：${e.message}`);
                }
            } catch {
                console.warn("unhandled 捕获了一个错误：", e);
            }
        }

        const STEAM_ORDER_SCALE_TEMPLATE = "<span class=\"f_12px f_Bold l_Right steam_temp steam_order_scale\"></span>";
        const STEAM_SOLD_NUMBER_TEMPLATE = "<span class=\"f_12px c_Green f_Bold l_Right steam_temp steam_sold_number\"></span>";
        const STEAM_ORDER_NUMBER_TEMPLATE = "<span class=\"f_12px c_Gray f_Bold l_Right steam_temp steam_order_number\"></span>";
        const ERROR_TEMPLATE = "<span class=\"f_12px c_Error f_Bold l_Right steam_temp steam_order_number_error\"></span>";
        const WARNING_TEMPLATE = "<span class=\"f_12px c_Orange f_Bold l_Right steam_temp steam_order_number_error\"></span>";
        const INFO_TEMPLATE = "<span class=\"f_12px c_Blue f_Bold l_Right steam_temp steam_order_number_error\"></span>";
        const HIGHLIGHT_TEMPLATE = "<span class=\"f_12px c_Highlight f_Bold l_Right steam_temp steam_order_number_error\"></span>";
        const ENHANCEMENT_SUPPORT_LIST = Array("rifle", "knife", "pistol", "smg", "machinegun", "shotgun", "hands");
        const DEFAULT_CONFIG = {
            maxRange: 1,
            minRange: 0.63,
            needSort: null,
            pageSize: 20,
            reverseSticker: false,
            orderFloatLeft: false,
            overrideSortRule: false,
            sortAfterAllDone: true,
            marketColorLow: "#ff1e1e",
            marketColorHigh: "#5027ff",
            steamCurrency: "USD",
            currencyEffectCalculate: false,
            displaySoldNumber: false,
            buffSellThreshold: 0,
            cardPrice: 1,             // 一百美金人民币卡价
            helperCardPrice: 5.75,    // 设置页面的卡价输入框
            reCalcProfitMargin: 15    // 反推利润率
        };
        let tag_class = {
            "崭新出厂": "tag_csgo_wearcategory0",
            "略有磨损": "tag_csgo_wearcategory1",
            "久经沙场": "tag_csgo_wearcategory2",
            "破损不堪": "tag_csgo_wearcategory3",
            "战痕累累": "tag_csgo_wearcategory4"
        }

        const g_rgCurrencyData = { "AED": { "strCode": "AED", "eCurrencyCode": 32, "strSymbol": "AED", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "ARS": { "strCode": "ARS", "eCurrencyCode": 34, "strSymbol": "ARS$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ",", "strThousandsSeparator": ".", "strSymbolAndNumberSeparator": " " }, "AUD": { "strCode": "AUD", "eCurrencyCode": 21, "strSymbol": "A$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "BRL": { "strCode": "BRL", "eCurrencyCode": 7, "strSymbol": "R$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ",", "strThousandsSeparator": ".", "strSymbolAndNumberSeparator": " " }, "CAD": { "strCode": "CAD", "eCurrencyCode": 20, "strSymbol": "CDN$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "CHF": { "strCode": "CHF", "eCurrencyCode": 4, "strSymbol": "CHF", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": " ", "strSymbolAndNumberSeparator": " " }, "CLP": { "strCode": "CLP", "eCurrencyCode": 25, "strSymbol": "CLP$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ",", "strThousandsSeparator": ".", "strSymbolAndNumberSeparator": " " }, "CNY": { "strCode": "CNY", "eCurrencyCode": 23, "strSymbol": "¥", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "COP": { "strCode": "COP", "eCurrencyCode": 27, "strSymbol": "COL$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ",", "strThousandsSeparator": ".", "strSymbolAndNumberSeparator": " " }, "CRC": { "strCode": "CRC", "eCurrencyCode": 40, "strSymbol": "₡", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ",", "strThousandsSeparator": ".", "strSymbolAndNumberSeparator": "" }, "CZK": { "strCode": "CZK", "eCurrencyCode": 44, "strSymbol": "Kč", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "DKK": { "strCode": "DKK", "eCurrencyCode": 45, "strSymbol": "kr.", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "EUR": { "strCode": "EUR", "eCurrencyCode": 3, "strSymbol": "€", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ",", "strThousandsSeparator": " ", "strSymbolAndNumberSeparator": "" }, "GBP": { "strCode": "GBP", "eCurrencyCode": 2, "strSymbol": "£", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": "" }, "HKD": { "strCode": "HKD", "eCurrencyCode": 29, "strSymbol": "HK$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "HRK": { "strCode": "HRK", "eCurrencyCode": 43, "strSymbol": "kn", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "HUF": { "strCode": "HUF", "eCurrencyCode": 46, "strSymbol": "Ft", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "IDR": { "strCode": "IDR", "eCurrencyCode": 10, "strSymbol": "Rp", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ".", "strThousandsSeparator": " ", "strSymbolAndNumberSeparator": " " }, "ILS": { "strCode": "ILS", "eCurrencyCode": 35, "strSymbol": "₪", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": "" }, "INR": { "strCode": "INR", "eCurrencyCode": 24, "strSymbol": "₹", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "JPY": { "strCode": "JPY", "eCurrencyCode": 8, "strSymbol": "¥", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "KRW": { "strCode": "KRW", "eCurrencyCode": 16, "strSymbol": "₩", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "KWD": { "strCode": "KWD", "eCurrencyCode": 38, "strSymbol": "KD", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "KZT": { "strCode": "KZT", "eCurrencyCode": 37, "strSymbol": "₸", "bSymbolIsPrefix": false, "bWholeUnitsOnly": true, "strDecimalSymbol": ",", "strThousandsSeparator": " ", "strSymbolAndNumberSeparator": "" }, "MXN": { "strCode": "MXN", "eCurrencyCode": 19, "strSymbol": "Mex$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "MYR": { "strCode": "MYR", "eCurrencyCode": 11, "strSymbol": "RM", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": "" }, "NOK": { "strCode": "NOK", "eCurrencyCode": 9, "strSymbol": "kr", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ",", "strThousandsSeparator": ".", "strSymbolAndNumberSeparator": " " }, "NZD": { "strCode": "NZD", "eCurrencyCode": 22, "strSymbol": "NZ$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "PEN": { "strCode": "PEN", "eCurrencyCode": 26, "strSymbol": "S/.", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": "" }, "PHP": { "strCode": "PHP", "eCurrencyCode": 12, "strSymbol": "P", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": "" }, "PLN": { "strCode": "PLN", "eCurrencyCode": 6, "strSymbol": "zł", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ",", "strThousandsSeparator": " ", "strSymbolAndNumberSeparator": "" }, "QAR": { "strCode": "QAR", "eCurrencyCode": 39, "strSymbol": "QR", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "RMB": { "strCode": "RMB", "eCurrencyCode": 23, "strSymbol": "¥", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "RON": { "strCode": "RON", "eCurrencyCode": 47, "strSymbol": "lei", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "RUB": { "strCode": "RUB", "eCurrencyCode": 5, "strSymbol": "pуб.", "bSymbolIsPrefix": false, "bWholeUnitsOnly": true, "strDecimalSymbol": ",", "strThousandsSeparator": "", "strSymbolAndNumberSeparator": " " }, "SAR": { "strCode": "SAR", "eCurrencyCode": 31, "strSymbol": "SR", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "SEK": { "strCode": "SEK", "eCurrencyCode": 33, "strSymbol": "kr", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "SGD": { "strCode": "SGD", "eCurrencyCode": 13, "strSymbol": "S$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": "" }, "THB": { "strCode": "THB", "eCurrencyCode": 14, "strSymbol": "฿", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": "" }, "TRY": { "strCode": "TRY", "eCurrencyCode": 17, "strSymbol": "TL", "bSymbolIsPrefix": false, "bWholeUnitsOnly": false, "strDecimalSymbol": ",", "strThousandsSeparator": ".", "strSymbolAndNumberSeparator": " " }, "TWD": { "strCode": "TWD", "eCurrencyCode": 30, "strSymbol": "NT$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": " " }, "UAH": { "strCode": "UAH", "eCurrencyCode": 18, "strSymbol": "₴", "bSymbolIsPrefix": false, "bWholeUnitsOnly": true, "strDecimalSymbol": ",", "strThousandsSeparator": " ", "strSymbolAndNumberSeparator": "" }, "USD": { "strCode": "USD", "eCurrencyCode": 1, "strSymbol": "$", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": ",", "strSymbolAndNumberSeparator": "" }, "UYU": { "strCode": "UYU", "eCurrencyCode": 41, "strSymbol": "$U", "bSymbolIsPrefix": true, "bWholeUnitsOnly": true, "strDecimalSymbol": ",", "strThousandsSeparator": ".", "strSymbolAndNumberSeparator": "" }, "VND": { "strCode": "VND", "eCurrencyCode": 15, "strSymbol": "₫", "bSymbolIsPrefix": false, "bWholeUnitsOnly": true, "strDecimalSymbol": ",", "strThousandsSeparator": ".", "strSymbolAndNumberSeparator": "" }, "ZAR": { "strCode": "ZAR", "eCurrencyCode": 28, "strSymbol": "R", "bSymbolIsPrefix": true, "bWholeUnitsOnly": false, "strDecimalSymbol": ".", "strThousandsSeparator": " ", "strSymbolAndNumberSeparator": " " } }
        const g_rgWalletInfo = {
            "wallet_currency": 23,
            "wallet_country": "CN",
            "wallet_state": "",
            "wallet_fee": "1",
            "wallet_fee_minimum": "1",
            "wallet_fee_percent": "0.05",
            "wallet_publisher_fee_percent_default": "0.10",
            "wallet_fee_base": "0",
            "wallet_balance": "20028",
            "wallet_delayed_balance": "0",
            "wallet_max_balance": "1300000",
            "wallet_trade_max_balance": "1170000"
        }

        var bidPrice = {};
        var added_st_box_flag = false;                          // 用于控制 饰品市场页面 st求购价显示的标志
        var helper_config = loadConfig();
        var steamCurrency;
        var exchangeRate = GM_getValue("exchangeRate") || {
            FtoC: 1,
            CtoF: 1,
            time_next_update_unix: 0,
            time_update_unix: 0
        };
        var ajaxTimeout = 20000;
        var steamConnection = undefined;
        var steamFailedTimes = 0;
        var market_color_high = [];
        var market_color_low = [];
        var itemCount = 0;
        var itemNum = 0;
        var needSort;

        // 翻页类的操作没有重新加载的必要，用var可以直接当缓存用，不过只适用某个具体商品详情页
        var steam_lowest_sell_order = 0;     // steam最低出售价
        var steam_highest_buy_order = 0;     // steam最高求购价

        // toast CSS
        GM_addStyle(".jq-toast-wrap{display:block;position:fixed;width:250px;pointer-events:none!important;margin:0;padding:0;letter-spacing:normal;z-index:9000!important}.jq-toast-wrap *{margin:0;padding:0}.jq-toast-wrap.bottom-left{bottom:20px;left:20px}.jq-toast-wrap.bottom-right{bottom:20px;right:40px}.jq-toast-wrap.top-left{top:20px;left:20px}.jq-toast-wrap.top-right{top:20px;right:74px}.jq-toast-single{display:block;width:100%;padding:10px;margin:0 0 5px;border-radius:4px;font-size:15px;font-family:arial,sans-serif;line-height:18px;position:relative;pointer-events:all!important;background-color:#444;color:white;white-space:normal;word-break:break-all;overflow:hidden}.jq-toast-single hr{border:1px solid #fff;margin:4px 0}.jq-toast-single h2{font-family:arial,sans-serif;font-size:18px;font-weight:bold;margin:0 0 7px;background:0;color:inherit;line-height:inherit;letter-spacing:normal}.jq-toast-single a{color:#eee;text-decoration:none;font-weight:bold;border-bottom:1px solid white;margin-right:8px}.jq-toast-single ul{margin:0 0 0 15px;background:0;padding:0}.jq-toast-single ul li{list-style-type:disc!important;line-height:17px;background:0;margin:0;padding:0;letter-spacing:normal}.close-jq-toast-single{position:absolute;top:2px;right:5px;font-size:22px;cursor:pointer}.jq-toast-loader{display:block;position:absolute;bottom:0;height:4px;width:0;left:0;background:#000!important;opacity:.4}.jq-toast-loaded{width:100%}.jq-has-icon{padding:10px 10px 10px 43px;background-repeat:no-repeat;background-position:10px}.jq-icon-info{background-image:url('');background-color:#2878c1e6;color:#d9edf7;border-color:#bce8f1}.jq-icon-warning{background-image:url('');background-color:#F89406cc;color:#fcf8e3;border-color:#faebcc}.jq-icon-error{background-image:url('');background-color:#d4372fcc;color:#f2dede;border-color:#ebccd1}.jq-icon-success{background-image:url('');color:#dff0d8;background-color:#059850e6;border-color:#d6e9c6}.jq-icon-info:hover{background-color:#2878c1}.jq-icon-warning:hover{background-color:#e48b06}.jq-icon-error:hover{background-color:#c53d36}.jq-icon-success:hover{background-color:#059850}");
        // 右侧浮动栏点击设置按钮时要显示的界面（默认为 display: none;）
        GM_addStyle(".helper_importantA{font-size:22px;font-weight:bold;color:#ffa914 !important}.helper_importantA:hover{color:#ff2c2c !important}.helper-setting input[type=number]{max-width:70px}input[type=\"number\"]{-moz-appearance:textfield}.helper-setting-shadow{position:fixed;justify-content:center;align-items:center;display:none;z-index:100;top:0;right:0;bottom:0;left:0;margin:0;background:#00000066}.helper-setting{background:#fff;border-radius:5px;padding:30px 40px 10px;top:25%;opacity:0.95;}.w-Checkbox.helper-setting-option>span:first-child{margin:0!important;font-size:14px}.helper-setting-steamConnection i.icon{margin-left:0!important}.helper-setting .list_tb span,.helper-setting .list_tb i.icon{margin-left:12px}.helper-setting .icon_status_progressing{animation:rotate-L 1.5s linear infinite;-webkit-animation:rotate-L 1.5s linear infinite}.helper-setting>.list_tb tr:last-child>td{border-bottom:0}.helper-setting td.setting-title{height:0;border:0;padding:5px 0 0 0}");
        $("body").append(`<div class="cont_main helper-setting-shadow">
        <div class="helper-setting">
        <b>基础设定</b>
        <span id="helper-version" style="float: right;">插件版本：</span>
        <table class="list_tb"><tbody>
            <tr>
                <td class="t_Left c_Gray">STEAM连接性：</td>
                <td class="t_Left helper-setting-steamConnection">
                    <span class="c_Yellow"><i class="icon icon_status_waiting"></i>未知</span>
                </td>
                <td class="t_Right">
                    <span class="c_DGrey steamConnectionCountdown" style="display: none;"></span>
                    <a href="javascript:void(0);" id="helper-setting-checkBtn" class="i_Btn i_Btn_small">检测</a>
                </td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">Steam参考货币</td>
                <td class="t_Left" colspan="2">
                    <span>
                        <div id="helper-setting-currency" class="w-Select helper-setting-option" data-option-target="steamCurrency" style="width: 120px; visibility: visible;">
                            <h3 style="margin:0;font-weight:normal;">默认</h3>
                            <i class="icon icon_drop"></i>
                            <ul style="width: 120px;height: 200px;overflow: auto;" class="steam-currency-selector"></ul>
                        </div>
                    </span>
                    <i class="icon icon_qa j_tips_handler helper-warning-currency" data-title="说明：" data-content="选择获取steam数据时使用什么货币，会影响税后价格、求购价格等\n默认为CNY（￥）" data-direction="right"></i>
                    <span>
                        <div id="helper-setting-currencyEffectCalculate" class="w-Checkbox helper-setting-option" data-option-target="currencyEffectCalculate" value="">
                            <span value="true"><i class="icon icon_checkbox"></i>无视汇率</span>
                        </div>
                    </span>
                    <i class="icon icon_qa j_tips_handler helper-warning-currency" data-title="说明：" data-content="勾选后不会将外币转回人民币进行计算（无特殊需求不用开）" data-direction="right"></i>
                </td>
            </tr>
            </tbody>
            <tbody>
            <tr>
                <td class="t_Left setting-title" colspan="3">
                    <b>选品设定</b>
                </td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">当前选品卡价</td>
                    <td class="t_Left">
                        <span>
                        <input type="number" id="helper-setting-pageCardPrice" data-option-target="helperCardPrice" class="i_Text helper-setting-option"></span>
                        <i class="icon icon_qa j_tips_handler helper-warning-sell-threshold" data-title="说明：" data-content="左侧公式联动窗口的卡价在这里设置！！" data-direction="right"></i>
                    </td>
                <td class="t_Right"></td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">当前反推利润率</td>
                    <td class="t_Left">
                        <span>
                        <input type="number" id="helper-setting-reCalcProfitMargin" data-option-target="reCalcProfitMargin" class="i_Text helper-setting-option"></span>
                        <i class="icon icon_qa j_tips_handler helper-warning-sell-threshold" data-title="说明：" data-content="修改这个反推利润率会导致页面中所有的商品重新计算一次st求购价" data-direction="right"></i>
                    </td>
                <td class="t_Right"></td>
            </tr>
            </tbody>
            <tbody>
            <tr>
                <td class="t_Left setting-title" colspan="3">
                    <b>市场页设定</b>
                </td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">在售数量门槛</td>
                <td class="t_Left">
                    <span>
                    <input type="number" id="helper-setting-buffSellThreshold" data-option-target="buffSellThreshold" class="i_Text helper-setting-option" min="0" step="1"></span>
                    <i class="icon icon_qa j_tips_handler helper-warning-sell-threshold" data-title="说明：" data-content="在售量小于设定值的商品会被略过，可以减少对steam的请求" data-direction="right"></i>
                </td>
                <td class="t_Right"></td>
            </tr>
            <tr>
                <td class="t_Left c_Gray" width="120">覆盖排序规则</td>
                <td class="t_Left">
                    <span>
                        <div id="helper-setting-stickerSort" class="w-Checkbox helper-setting-option" data-option-target="overrideSortRule" value="">
                            <span value="true"><i class="icon icon_checkbox"></i>启用 </span>
                        </div>
                    </span>
                    <i class="icon icon_qa j_tips_handler" data-title="说明：" data-content="开启后使用buff排序时插件不进行排序（可以手动排，不影响设置）" data-direction="right"></i>
                </td>
                <td class="t_Right"></td>
            </tr>
            <tr>
                <td class="t_Left c_Gray" width="120">完成后排序</td>
                <td class="t_Left">
                    <span>
                        <div id="helper-setting-sortAfterAllDone" class="w-Checkbox helper-setting-option" data-option-target="sortAfterAllDone" value="">
                            <span value="true"><i class="icon icon_checkbox"></i>启用 </span>
                        </div>
                    </span>
                    <i class="icon icon_qa j_tips_handler" data-title="说明：" data-content="等待所有饰品比例都加载完成后再进行排序" data-direction="right"></i>
                </td>
                <td class="t_Right"></td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">默认排序规则</td>
                <td class="t_Left">
                    <span>
                        <div id="helper-setting-sortRule" class="w-Select helper-setting-option" data-option-target="needSort" style="visibility: visible;">
                            <h3 style="margin:0;font-weight:normal;">不排序</h3>
                            <i class="icon icon_drop"></i>
                            <ul style="width: 130px;">
                                <li value="null">不排序</li>
                                <li value="buff-sort_asc">按buff比例从低到高</li>
                                <li value="buff-sort_desc">按buff比例从高到低</li>
                                <li value="order-sort_asc">按求购比例从低到高</li>
                                <li value="order-sort_desc">按求购比例从高到低</li>
                            </ul>
                        </div>
                    </span>
                </td>
                <td class="t_Right">
                    <i class="icon icon_qa j_tips_handler" data-title="说明：" data-content="只能排序当前加载的页面，全局排序请自行寻找其他插件" data-direction="right"></i>
                </td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">每页显示数量</td>
                <td class="t_Left">
                    <span>
                        <input type="number" id="helper-setting-pageSize" data-option-target="pageSize" class="i_Text helper-setting-option" min="1" max="80" step="1">
                    </span>
                    <i class="icon icon_qa j_tips_handler helper-warning-pageNum" data-title="修改每页显示数量" data-content="可能增加封号概率，小白勿用，默认值20，最大值80" data-direction="right"></i>
                </td>
                <td class="t_Right"></td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">渐变色</td>
                <td class="t_Left" colspan="2">
                    <span class="c_DGray">最小 <input type="color" id="helper-setting-marketColorLow" data-option-target="marketColorLow" class="helper-setting-option"></span>
                        <i class="icon icon_qa j_tips_handler" data-title="" data-content="渐变最小值：比例越接近最小值（默认是0.63）会越趋近这个颜色\n渐变最大值：比例越接近最大值（默认是1）会越趋近这个颜色" data-direction="bottom"></i>
                    <span class="c_DGray">最大 <input type="color" id="helper-setting-marketColorHigh" data-option-target="marketColorHigh" class="helper-setting-option"></span>
                </td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">比例极值</td>
                <td class="t_Left" colspan="2">
                    <span class="c_DGray">最小 <input type="number" id="helper-setting-minRange" data-option-target="minRange" class="i_Text helper-setting-option" min="0" max="1" step="0.01"></span>
                    <i class="icon icon_qa j_tips_handler" data-title="" data-content="比例最小值：小于等于这个值的比例会直接渲染成最小值渐变色\n比例最大值：大于等于这个值的比例会直接渲染成最大值渐变色" data-direction="bottom"></i>
                    <span class="c_DGray">最大 <input type="number" id="helper-setting-maxRange" data-option-target="maxRange" class="i_Text helper-setting-option" min="1" max="100"></span>
                </td>
            </tr>
            </tbody>
            <tbody>
            <tr>
                <td class="t_Left setting-title" colspan="3"><b>商品页设定</b></td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">求购列表靠左显示</td>
                <td class="t_Left">
                    <span>
                        <div id="helper-setting-orderFloatLeft" class="w-Checkbox helper-setting-option" data-option-target="orderFloatLeft">
                            <span value="true"><i class="icon icon_checkbox"></i>启用 </span>
                        </div>
                    </span>
                    <i class="icon icon_qa j_tips_handler" data-title="说明：" data-content="决定求购列表是否显示在左侧（饰品图片之后）" data-direction="right"></i>
                </td>
                <td class="t_Right"></td>
            </tr>
            <tr>
                <td class="t_Left c_Gray">反向贴纸顺序</td>
                <td class="t_Left">
                    <span>
                        <div id="helper-setting-reverseSticker" class="w-Checkbox helper-setting-option" data-option-target="reverseSticker">
                            <span value="true"><i class="icon icon_checkbox"></i>启用 </span>
                        </div>
                    </span>
                    <i class="icon icon_qa j_tips_handler" data-title="说明：" data-content="将饰品贴纸的顺序倒转，保持和检视时枪上的顺序一样" data-direction="right"></i>
                </td>
                <td class="t_Right"></td>
            </tr>
            <tr>
                <td class="t_Center" colspan="3">
                    <a href="https://greasyfork.org/zh-CN/scripts/410137" class="helper_importantA">插件免费 请勿上当 官网安装 防止盗号</a>
                    <br />
                </td>
            </tr>
            <tr>
                <td class="t_Center" colspan="3">
                    <a href="https://greasyfork.org/zh-CN/scripts/410137">插件官网</a>
                    <span><a href="https://greasyfork.org/zh-CN/scripts/410137#support">常见问题</a></span>
                    <span><a href="javascript:void(0);" id="helper-setting-resetAll" class="i_Btn i_Btn_small">恢复默认设置</a></span>
                    <span><a href="https://greasyfork.org/zh-CN/scripts/410137#additional-info">使用教程</a></span>
                    <span><a href="https://greasyfork.org/zh-CN/scripts/410137/feedback#post-discussion">问题反馈</a>
                    </span>
                </td>
            </tr>
            </tbody>
        </table>
        </div>
        </div>`);

        // 检测steam连接性(暂时保留)
        // GM_xmlhttpRequest({
        //     url: "https://steamcommunity.com/market/",
        //     timeout: 200000,
        //     method: "get",
        //     onload: function (res) {
        //         if (res && res.status == 200) {
        //             let endTime = new Date().getTime();
        //             console.log("开头检测steam连接性正常", res, endTime);
        //         } else {
        //             console.log("检测steam连接性出错：状态错误", res);
        //         }
        //     },
        //     onerror: function (err) {
        //         console.log("检测steam连接性出错：连接错误", err);
        //     },
        //     ontimeout: function () {
        //         console.log("检测steam连接性出错：尝试超时");
        //     }
        // });

        // 获取steam账号信息
        getSteamAccountInfo();

        // 添加左侧计算利润小窗口（ST市场快捷提交求购单窗口）
        async function add_calc_profit_box() {
            GM_xmlhttpRequest({
                url: "http://buffyouhou.web3v.vip",
                timeout: 20000,
                method: 'get',
                onload: function (res) {
                    if (res && res.status == 200) {
                        info("计算利润小窗口：");
                        info(res);
                        $("body").append(res.responseText);
                        // 添加计算利润小窗口联动计算功能
                        fast_calc_box_func();
                        // 添加设置账单地址功能
                        add_set_account_address_btn();
                        // 添加打开获取所有求购单窗口功能
                        add_get_all_order_list_btn();
                        // 添加下单按钮的功能
                        add_create_order_btn();
                        // 添加查看选品库功能
                        add_check_item_library_btn();
                    } else {
                        console.log("检测左侧小窗口连接性出错：状态错误", res);
                    }
                },
                onerror: function (err) {
                    console.log("检测左侧小窗口连接性出错：连接错误", err);
                },
                ontimeout: function () {
                    console.log("检测左侧小窗口连接性出错：尝试超时");
                }
            });
        }

        await add_calc_profit_box();

        // 左侧计算利润小窗口的样式
        GM_addStyle(`.calc-profit-box, .calc-profit-box * {
            margin: 0;
            padding: 0;
        }
        .calc-profit-box {
            background-color: rgb(244, 244, 244);
            width: 170px;
            position: absolute;
            left: 10px;
            top: 10px;
            z-index: 100;
            font-size: 10px;
            border-radius: 4px;
            user-select: none;
        }
        .calc-profit-box .tbd {
            background-color: #fff;
            margin: 2px;
            padding: 2px;
        }
        .calc-profit-box .trow {
            background-color: #fff;
            padding: 6px;
        }
        .calc-profit-box .flex-tr {
            display: flex;
            flex-direction: row;
        }
        .calc-profit-box .tdata {
            width: 50%;
        }
        .calc-profit-btn {
            color: #fff;
            background-color: rgb(66, 113, 198);
            border-radius: 2px;
            padding: 3px 7px;
        }
        .calc-profit-stitle {
            color: rgb(140, 140, 140);
        }
        .calc-profit-box input {
            width: 65px;
            border: none;
            border-bottom: 1px solid #ccc;
        }
        .center-box {
            text-align: center;
        }`);

        // 设置账单地址界面的样式
        GM_addStyle(`.setting_steam_account_address_shadow {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.2);
            font-size: 15px;
            user-select: none;
            z-index: 1000;
        }
        .setting_steam_account_address_shadow .setting_steam_account_address {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            min-width: 500px;
            width: 595px;
            height: 500px;
            background-color: #fff;
            border-radius: 5px;
            padding: 20px;
            overflow-y: scroll;
            z-index: 1000;
        }
        .setting_steam_account_address_shadow .setting_steam_account_address > div {
            margin-bottom: 25px;
            width: 100%;
        }
        .setting_steam_account_address_shadow .line-title {
            font-weight: 900;
        }
        .setting_steam_account_address_shadow .steam-login-info {
            font-size: 12px;
        }
        .setting_steam_account_address_shadow button {
            color: #fff;
            background-color: rgb(63, 110, 190);
            padding: 3px 5px;
            border: none;
            margin-left: 10px;
        }
        .setting_steam_account_address_shadow .line-text {
            width: 70px;
            color: rgb(138, 138, 138);
        }
        .setting_steam_account_address_shadow .line-input {
            width: 170px;
            height: 32px;
        }
        .setting_steam_account_address_shadow .line-input input {
            width: 100%;
            height: 100%;
            border: #00000040 solid 1px;
            border-radius: 3px;
        }
        .setting_steam_account_address_shadow .steam-name, .steam-address, .steam-city, .steam-country {
            display: flex;
            justify-content: space-between;
        }
        .setting_steam_account_address_shadow .steam-country {
            margin-bottom: 15px !important;
            padding-bottom: 15px;
            border-bottom: #00000040 solid 1px;
        }
        .setting_steam_account_address_shadow .steam-name .line-text {
            width: 70px;
            line-height: 32px;
        }
        .setting_steam_account_address_shadow .bottom-line {
            text-align: center;
        }
        .setting_steam_account_address_shadow #zhousheng {
            width: 176px;
            height: 36px;
        }`);

        // 查询已提交订购单数额界面的样式
        GM_addStyle(`.select_steam_commited_orders_shadow {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.2);
            font-size: 15px;
            user-select: none;
            z-index: 1000;
        }
        .select_steam_commited_orders_shadow .select_steam_commited_orders {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            min-width: 500px;
            width: 900px;
            height: 500px;
            background-color: #fff;
            border-radius: 5px;
            padding: 20px;
            overflow-y: scroll;
            z-index: 1000;
        }
        .select_steam_commited_orders_shadow .topline {
            font-size: 14px;
        }
        .select_steam_commited_orders_shadow .topline > span:first-child {
            font-weight: 900;
        }
        .select_steam_commited_orders_shadow .steamCommitedOrdersTable {
            width: 100%;
            margin: 0 auto;
            font-size: 12px;
            white-space: nowrap;
        }
        .select_steam_commited_orders_shadow .orderID {
            width: 25%;
        }
        .select_steam_commited_orders_shadow .goodsName {
            width: 35%;
        }
        .select_steam_commited_orders_shadow .ST-Link {
            width: 15%;
        }
        .select_steam_commited_orders_shadow .steamCommitedOrdersTbody {
            display: none;
        }
        .select_steam_commited_orders_shadow .steamCommitedOrdersTbody tr {
            height: 40px;
        }
        .select_steam_commited_orders_shadow .loadingSteamCommitedOrdersTbody {
            text-align: center;
            padding: 100px;
        }
        .select_steam_commited_orders_shadow .btnline {
            text-align: center;
            padding-bottom: 10px;
            border-bottom: #00000040 solid 1px;
        }
        .select_steam_commited_orders_shadow button {
            color: #fff;
            background-color: rgb(63, 110, 190);
            padding: 3px 5px;
            border: none;
            margin-left: 10px;
        }
        .select_steam_commited_orders_shadow .bottomline {
            text-align: center;
            font-size: 12px;
            margin: 20px;
            position: absolute;
            left: 50%;
            bottom: 0;
            transform: translateX(-50%);
        }
        .select_steam_commited_orders_shadow td.orderID span:hover {
            color: rgb(238,162,14);
            font-weight: 900;
        }`);

        // 查看选品库页面样式
        GM_addStyle(`.check_item_library_shadow {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            overflow: hidden;
            background-color: rgba(0, 0, 0, 0.2);
            font-size: 15px;
            user-select: none;
            z-index: 1000;
        }
        .check_item_library_shadow .check_item_library {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            min-width: 500px;
            width: 1000px;
            height: 500px;
            background-color: #fff;
            border-radius: 5px;
            padding: 20px;
            z-index: 1000;
        }
        .check_item_library_shadow .line-title {
            font-weight: 900;
            margin-bottom: 30px;
        }
        .check_item_library_shadow .table-box {
            width: 100%;
            height: 80%;
            overflow-y: scroll;
        }
        .check_item_library_shadow .table-box table {
            width: 100%;
            text-align: center;
        }
        .check_item_library_shadow .table-box table tr {
            height: 40px;
        }
        .check_item_library_shadow .bottom_btn_line {
            text-align: center;
            margin-top: 15px;
        }
        .check_item_library_shadow .bottom_btn_line button {
            margin: 10px;
            padding: 6px 10px;
            color: #fff;
            background-color: rgb(63, 110, 190);
            border: none;
        }`);

        // 设置账单地址界面
        $("body").append(`<div class="setting_steam_account_address_shadow">
            <div class="setting_steam_account_address">
                <div class="steam-login-line">
                    <span class="line-title">账单地址设定：</span>
                    <span class="steam-login-info">
                        当前登录（
                        <span class="steamID">正在获取...</span>
                        ，账号：
                        <span class="steamUserName">正在获取...</span>
                        ）
                    </span>
                    <button class="updateSteamLoginBtn">更新</button>
                </div>
                <div>
                    <span class="line-title">姓名</span>
                </div>
                <div class="steam-name">
                    <span class="line-text">名</span>
                    <span class="line-input">
                        <input type="text">
                    </span>
                    <span class="line-text">姓</span>
                    <span class="line-input">
                        <input type="text">
                    </span>
                </div>
                <div>
                    <span class="line-title">地址</span>
                </div>
                <div class="steam-address">
                    <span class="line-text">账单地址</span>
                    <span class="line-input">
                        <input type="text">
                    </span>
                    <span class="line-text">账单地址<br/>行2</span>
                    <span class="line-input">
                        <input type="text">
                    </span>
                </div>
                <div>
                    <span class="line-title">城市</span>
                </div>
                <div class="steam-city">
                    <span class="line-text">城市</span>
                    <span class="line-input">
                        <input type="text">
                    </span>
                    <span class="line-text">州/省</span>
                    <span class="line-input">
                        <select name="" id="zhousheng">
                            <option value="AL">Alabama</option>
                            <option value="AK">Alaska</option>
                            <option value="AS">American Samoa</option>
                            <option value="AZ">Arizona</option>
                            <option value="AR">Arkansas</option>
                            <option value="AA">Armed Forces Americas</option>
                            <option value="AE">Armed Forces Europe</option>
                            <option value="AP">Armed Forces Pacific</option>
                            <option value="CA">California</option>
                            <option value="CO">Colorado</option>
                            <option value="CT">Connecticut</option>
                            <option value="DE">Delaware</option>
                            <option value="DC">District Of Columbia</option>
                            <option value="FM">Federated States Of Micronesia</option>
                            <option value="FL">Florida</option>
                            <option value="GA">Georgia</option>
                            <option value="GU">Guam</option>
                            <option value="HI">Hawaii</option>
                            <option value="ID">Idaho</option>
                            <option value="IL">Illinois</option>
                            <option value="IN">Indiana</option>
                            <option value="IA">Iowa</option>
                            <option value="KS">Kansas</option>
                            <option value="KY">Kentucky</option>
                            <option value="LA">Louisiana</option>
                            <option value="ME">Maine</option>
                            <option value="MH">Marshall Islands</option>
                            <option value="MD">Maryland</option>
                            <option value="MA">Massachusetts</option>
                            <option value="MI">Michigan</option>
                            <option value="MN">Minnesota</option>
                            <option value="MS">Mississippi</option>
                            <option value="MO">Missouri</option>
                            <option value="MT">Montana</option>
                            <option value="NE">Nebraska</option>
                            <option value="NV">Nevada</option>
                            <option value="NH">New Hampshire</option>
                            <option value="NJ">New Jersey</option>
                            <option value="NM">New Mexico</option>
                            <option value="NY">New York</option>
                            <option value="NC">North Carolina</option>
                            <option value="ND">North Dakota</option>
                            <option value="MP">Northern Mariana Islands</option>
                            <option value="OH">Ohio</option>
                            <option value="OK">Oklahoma</option>
                            <option value="OR">Oregon</option>
                            <option value="PW">Palau</option>
                            <option value="PA">Pennsylvania</option>
                            <option value="PR">Puerto Rico</option>
                            <option value="RI">Rhode Island</option>
                            <option value="SC">South Carolina</option>
                            <option value="SD">South Dakota</option>
                            <option value="TN">Tennessee</option>
                            <option value="TX">Texas</option>
                            <option value="UT">Utah</option>
                            <option value="VT">Vermont</option>
                            <option value="VI">Virgin Islands</option>
                            <option value="VA">Virginia</option>
                            <option value="WA">Washington</option>
                            <option value="WV">West Virginia</option>
                            <option value="WI">Wisconsin</option>
                            <option value="WY">Wyoming</option>
                        </select>
                    </span>
                </div>
                <div>
                    <span class="line-title">国家地区</span>
                </div>
                <div class="steam-country">
                    <span class="line-text">邮政编码</span>
                    <span class="line-input">
                        <input type="text">
                    </span>
                    <span class="line-text">国家</span>
                    <span class="line-input">
                        <input type="text" disabled value="美国">
                    </span>
                </div>
                <div class="bottom-line">
                    请在上面填写你在steam市场下单用的账单地址信息
                    <button>恢复默认设置</button>
                </div>
            </div>
        </div>`);

        // 查询已提交订购单数额界面
        $("body").append(`<div class="select_steam_commited_orders_shadow">
            <div class="select_steam_commited_orders">
                <div class="topline">
                    <span>我的订购单查询列表（
                        <span class="steamID">获取中...</span>
                        ，账号：
                        <span class="steamUserName">获取中...</span>
                        ）：
                    </span>
                    <span>
                        共
                        <span class="steamCommitedOrderCount">??</span>
                        个，$
                        <span class="steamCommitedAllOrderPrice">??</span>
                    </span>
                </div>
                <table class="steamCommitedOrdersTable">
                    <thead>
                        <tr>
                            <th class="orderID">订单号（点击取消求购）</th>
                            <th class="goodsName">饰品名称</th>
                            <th>求购价格</th>
                            <th>求购数量</th>
                            <th>剩余数量</th>
                            <th class="ST-Link">ST链接</th>
                        </tr>
                    </thead>
                    <tbody class="steamCommitedOrdersTbody">
                        ...
                    </tbody>
                </table>
                <div class="loadingSteamCommitedOrdersTbody">
                    正在加载中。。。。。。
                </div>
                <div class="btnline">
                    <button>全部取消</button>
                </div>
                <div class="bottomline">
                    My buy orders
                </div>
            </div>
        </div>`);

        // 查看选品库页面
        $("body").append(`<div class="check_item_library_shadow">
            <div class="check_item_library">
                <div class="line-title">选品库<span style="color: gray; font-weight: 500;">（导入选品库之前，记得将选品库导出备份，导入后将覆盖原有的选品库）</span></div>
                <div class="table-box">
                    <table>
                        <thead>
                            <tr>
                                <th>选品名称</th>
                                <th>求购价格 (美元)</th>
                                <th>求购数量</th>
                                <th>st链接</th>
                                <th>当前购买状态</th>
                                <th>删除</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
                <div class="bottom_btn_line">
                    <button class="importAllItemBtn">导入选品库</button>
                    <button class="outputAllItemBtn">导出选品库</button>
                    <button class="deleteAllItemBtn">全部删除</button>
                    <button class="buyAllItemBtn">全部下单</button>
                </div>
            </div>
        </div>`);
        
        // 初始化货币
        initCurrency();
        // 添加翻页和设置按钮，初始化部分数据
        initHelper();

        // 更新汇率
        updateRate();
        // 添加计算利润小窗口联动计算功能
        // fast_calc_box_func();

        // 将替换在售大于1000个的商品
        // set_gt_1000_goods();

        // 添加账单地址设置按钮的点击行为
        // (function add_setting_steam_account_address_btn_listener() {
        //     let btn = document.querySelector("body > div.calc-profit-box > div:nth-child(1) > div:nth-child(2) > span");
        //     let box_shadow = document.querySelector('.setting_steam_account_address_shadow');
        //     if (!box_shadow || !btn) {
        //         setTimeout(add_setting_steam_account_address_btn_listener, 100);
        //         return ;
        //     }
        //     btn.addEventListener('click', function (e) {
        //         if (box_shadow.style.display == 'block') {
        //             box_shadow.style.display = 'none';
        //         } else {
        //             box_shadow.style.display = 'block';
        //             // 删除页面中原有的信息
        //             // 将更新后的信息展示出来
        //         }
        //     });
        // })();
        // 账单地址设置界面的事件绑定
        // (function add_setting_steam_account_address_shadow_listener() {
        //     let box_shadow = document.querySelector('.setting_steam_account_address_shadow');
        //     let box = document.querySelector('.setting_steam_account_address');

        //     if (!box_shadow || !box) {
        //         setTimeout(add_setting_steam_account_address_shadow_listener, 100);
        //         return ;
        //     }

        //     box_shadow.addEventListener('click', function (e) {
        //         box_shadow.style.display = 'none';
        //     });

        //     box.addEventListener('click', function (e) {
        //         e.stopPropagation();
        //     });
        // })();
        // // 查询已提交订购单数额按钮的点击行为
        // (function select_steam_commited_orders_btn_listener() {
        //     let btn = document.querySelector("body > div.calc-profit-box > div:nth-child(2) > div > span")
        //     let box_shadow = document.querySelector('.select_steam_commited_orders_shadow');
        //     if (!box_shadow || !btn) {
        //         setTimeout(select_steam_commited_orders_btn_listener, 100);
        //         return ;
        //     }
        //     btn.addEventListener('click', function (e) {
        //         if (box_shadow.style.display == 'block') {
        //             box_shadow.style.display = 'none';
        //         } else {
        //             box_shadow.style.display = 'block';
        //             // 删除页面中原有的信息
        //             // 将更新后的信息展示出来
        //         }
        //     });
        // })();
        // // 查询已提交订购单数额界面的事件绑定
        // (function select_steam_commited_orders_shadow_listener() {
        //     let box_shadow = document.querySelector('.select_steam_commited_orders_shadow');
        //     let box = document.querySelector('.select_steam_commited_orders');
        //     if (!box_shadow || !box) {
        //         setTimeout(select_steam_commited_orders_shadow_listener, 100);
        //         return ;
        //     }

        //     box_shadow.addEventListener('click', function (e) {
        //         box_shadow.style.display = 'none';
        //     });

        //     box.addEventListener('click', function (e) {
        //         e.stopPropagation();
        //     });
        // })();

        // 分支控制 商品详情页 与 饰品市场页面 的不同逻辑
        if (location.pathname.startsWith("/goods/")) {
            // 自带css
            GM_addStyle(".market_commodity_orders_header_promote {color: whitesmoke;}#steam_sold{margin-top:5px}#steam_order{margin-top:5px}#steam_order_error{margin-top:5px;font-size: medium;font-weight: bold;color: #ff1e3e;}.market_listing_price_with_fee{color: #ffae3a;font-size: 12px;margin-left: 6px;}");
            GM_addStyle(".steam-link{float:right;margin-top:3px}.detail-cont>.blank20{height:10px}");
            // 组件css
            GM_addStyle(".paymentIcon{padding:1px 17px 0 !important;position:absolute}a.j_shoptip_handler{margin-right:10px}.user-thum{margin: 0;}.list_tb_csgo>tr>th:first-child{width:5px}.list_tb_csgo>tr>th:nth-child(2){padding-right:9px}.list_tb_csgo>tr>th:nth-child(4){min-width:185px !important}.list_tb_csgo .pic-cont{width:112px;height:84px}.list_tb_csgo .pic-cont img{height:100%;}.csgo_sticker.has_wear{position:absolute;display: inline-block;margin:10px 0 0 270px}.csgo_sticker.has_wear .stickers{width:62px;height:48px;margin:0;background: 0;}.stag{margin:0 0 0 2px !important;padding: 4px 6px;float:none !important}.float_rank{color: green;}.stickers:hover{opacity:1!important}");
            GM_addStyle(".tooltip .tooltiptext{visibility:hidden;border: 1px solid #d0d0d0;width:128px;height:96px;background-color:#fbfbfbc7;position:absolute;z-index:60;bottom:100%;margin-left:-62px;border-radius:10px}.tooltip:hover .tooltiptext{visibility:visible}");
            // 求购列表css
            GM_addStyle(".market_commodity_orders_table.order_float_left{margin: 0 10px 0 0;float: left;}.market_commodity_orders_table{margin: 0 0 0 10px;height:100%;float:right;border-collapse:separate;background-color:rgba(0,0,0,0.3);}.market_commodity_orders_table tr:nth-child(even){background-color:#242b33}.market_commodity_orders_table td{text-align:center;padding:4px}.market_commodity_orders_table th{padding:4px;margin:0;text-align:center;font-size:16px;font-weight:normal}");
            // 求购警告css
            GM_addStyle('#steam_order .warning{ position: relative; margin: 0 0 0 4px; display: inline-flex; vertical-align: text-bottom; } #steam_order .warning .tips { visibility: hidden; position: absolute; width: 200px; top: 100%; left: 0; background: #111111; padding: 4px;} #steam_order:hover .warning .tips { visibility: visible; }');

            (function initSteamLink() {
                if (!document.querySelector(".detail-cont")) {
                    requestIdleCallback(initSteamLink, { timeout: 300 });
                    return;
                }
                $(".detail-pic").css("background-repeat", "round").children().width(250);
                if ($("#j_game-switcher").data("current") == "dota2") {
                    $(".detail-cont>p").append($(".detail-summ>a").clone().addClass("steam-link"));
                } else {
                    $(".detail-cont>div:first").append($(".detail-summ>a").clone().addClass("steam-link"));
                }

                // 适配 ”饰品比例计算脚本“ greasyfork.org/scripts/35597
                // 防止排版冲突混乱
                $(".detail-summ>a").hide();
                $(".detail-cont").css("margin-left", 0);
            })();

            $(document).ajaxSuccess(function (event, status, header, result) {
                if (/^\/api\/market\/goods\/sell_order/.exec(header.url) && result.data && result.data.goods_infos[getGoodsId()] && result.data.total_count) {
                    steamFailedTimes = 0;
                    buffHelperModule_inspestEnhancementCsgo(result.data);
                    buffHelperGoodsDetailScale(result.data);
                }
            });
            
            // 去除 “我要求购” 和 “我要出售” 按钮
            document.querySelector("body > div.market-list > div > div.detail-header.black > div.detail-cont > div.detail-summ > div").style.display = 'none';

        } else if (location.pathname.startsWith("/market/")) {
            // 主要样式
            GM_addStyle(".steam_temp{margin-top: inherit;}#sort_scale{display:inline-block;padding:0 6px 0 16px;cursor:pointer;height:32px;margin-left:5px;line-height:32px;text-align:center;border-radius:4px;min-width:60px;border:1px solid #45536c;color:#63779b;vertical-align:middle}#sort_scale.enabled{background:#45536c;color:#fff}.list_card li{padding-bottom:0}.list_card li h3{margin: 4px 8px;}.list_card li p{margin: 6px 8px;}.list_card li>p>span.l_Left{margin-top:inherit}.list_card li>p>strong.f_Strong{display:block;font-size:20px;min-height:20px;}.price_scale{padding-top:2px}");
            // 进度条样式
            GM_addStyle(".helper-loading{position:absolute;margin:11px}.helper-progress-bar{height:20px;background:linear-gradient(130deg, rgb(33 86 183 / 61%) 20%, rgb(15 116 187 / 35%) 85%, transparent);width:0;z-index:1000}");

            // 每个商品图片上st求购价的样式
            GM_addStyle("#j_list_card>ul>li>a {position: relative;}");
            GM_addStyle(".st-buymoney-box {position: absolute;left: 10px;bottom: 25px;padding: 3px 5px;background-color: #00000042;color: #fffc;}");
            
            // 价差率的样式
            GM_addStyle(".price-scale-box {position: absolute;left: 10px;bottom: 5px;padding: 3px 5px;background-color: #00000042;color: #fffc;}");

            $(document).ajaxSend(function (event, xhr, header, result) {
                if (/^\/api\/market\/goods/.exec(header.url)) {
                    header.url += "&page_size=" + helper_config.pageSize;
                    $(".helper-progress-bar").remove();
                    $(".helper-loading").remove();
                    steamFailedTimes = 0;
                }
            });
            $(document).ajaxSuccess(function (event, xhr, header, result) {
                if (/^\/api\/market\/goods/.exec(header.url) && result.data && result.data.total_count) {
                    buffHelperMarkerListScale(result.data.items);
                } else if (/\/api\/market\/sell_order\/top_bookmarked/.exec(header.url)) {
                    let warningTimes = GM_getValue("top_bookmarked-warning") || 0;
                    if (warningTimes < 3) {
                        GM_setValue("top_bookmarked-warning", ++warningTimes);
                        showMessage("插件不会在热门关注运行", "出售、求购板块都可以使用<br/>哪有人会关注溢价商品的比例呢？", "warning", 16000 - 4000 * warningTimes);
                    }
                }
            });
            if ($(".block-header>.l_Right").length == 0) {
                setTimeout(initSortBtn, 100);
            } else {
                initSortBtn();
            }

            
        }

        // 商品详情
        window.buffHelperGoodsDetailScale = function (data) {
            // 检测商品是否加载完成
            if ($("#market-selling-list").length == 0) {
                setTimeout(buffHelperGoodsDetailScale, 100);
                return;
            }
            console.log(GM_getValue("bidPrice"));
            $(".detail-cont").append("<i class=\"icon icon_uploading helper-loading\" style='margin: 5px;'></i>");
            goodsDetailLoadData(data);

            async function goodsDetailLoadData(data, secendTry) {
                // console.log("laoyu: 这里的data价格并不是表格里的", data);
                let price_list = $(".f_Strong");
                let isLogined = $("#navbar-cash-amount").length == 1;
                let isFirstTime = $(".good_scale").length == 0;
                let buff_item_id = getGoodsId();
                let Buff最低出售价 = GM_getValue("bidPrice")[buff_item_id].toFixed(2);   // 如果本行报错则进入浏览器点开 /market/页面等待所有商品加载完毕再进入 /goods/ 页面
                let Buff最低出售价人民币 = parseFloat(GM_getValue("bidPrice")[buff_item_id+"CNY"]);   // 人民币
                let 汇率 = GM_getValue("exchangeRate").FtoC
                // let 一百美金人民币卡价 = helper_config.cardPrice             // 1
                // let 一百美金人民币正价 = (100*汇率);
                // let 一美金实际成本 = (一百美金人民币卡价/一百美金人民币正价);  // 相当于一美金充值st进去后真正有多少钱
                let 一美金实际成本 = parseFloat(document.getElementById("helper-setting-pageCardPrice").value);   // 相当于一美金充值st进去后真正有多少钱

                console.log("汇率：", 汇率);
                // console.log("一百美金人民币正价：",一百美金人民币正价);
                // console.log("一百美金人民币卡价：",一百美金人民币卡价);
                console.log("一美金实际成本：",一美金实际成本);
                console.log("Buff商品ID",buff_item_id);
                console.log("Buff商品名",data.goods_infos[buff_item_id].name);
                console.log("Buff最低出售价",Buff最低出售价);
                console.log("Buff最低出售价人民币",Buff最低出售价人民币);
                let app_id = data.goods_infos[buff_item_id].appid;
                let hash_name = escape(data.goods_infos[buff_item_id].market_hash_name);
                let steamLink = $(".detail-summ>a").attr("href") || `https://steamcommunity.com/market/listings/${app_id}/${hash_name}`;
                let items = data.items;
                let steam_price_cny = data.goods_infos[buff_item_id].steam_price_cny * 100;
                let steam_min_price = null;
                if (isFirstTime) {
                    getSteamSoldNumber(app_id, hash_name).then((soldNumber) => {
                        let addStr = "";
                        if (soldNumber.success) {
                            addStr = `<div id="steam_sold" style="margin:5px">`;
                            addStr += `<span style="background-color:rgb(0,0,2);border-radius:3px;padding:5px;">`;
                            addStr += `有 <span class="market_commodity_orders_header_promote">${soldNumber.volume || 0}</span> 份在 24 小时内售出</span></div>`;
                        } else {
                            addStr = `<div id="steam_sold_error">获取steam销量失败，原因：${soldNumber.statusText.split("，")[0]}</div>`
                        }
                        $(".detail-cont").append(addStr);
                    });
                    let orderList = await getSteamOrderList(buff_item_id, steamLink);
                    steam_min_price = orderList.buy_order_graph[0][0];
                    if (orderList.success) {
                        steam_highest_buy_order = orderList.highest_buy_order && {
                            origin: orderList.highest_buy_order,
                            cny: FtoC(orderList.highest_buy_order)
                        };
                        steam_lowest_sell_order = orderList.lowest_sell_order && {
                            origin: orderList.lowest_sell_order,
                            cny: FtoC(orderList.lowest_sell_order)
                        };
                        if (orderList.buy_order_table != "") {
                            // $(".detail-cont").append(`<div id='steam_order'>${orderList.buy_order_summary}</div>`); // 原来的代码不适用了
                            (function () {
                                // 获取本页商品名称
                                let good_name = document.querySelector("body > div.market-list > div > div.detail-header.black > div.detail-cont > div:nth-child(1) > h1").innerText;
                                let url = `https://buff.163.com/api/market/goods?game=csgo&page_num=1&search=${good_name}&tab=selling&use_suggestion=0&_=1707105972779&page_size=20`;
                                let xhr = new XMLHttpRequest();
                                let text_color = "#ffae3a";
                                xhr.onreadystatechange = function () {
                                    if (xhr.readyState == 4 && xhr.status == 200) {
                                        let res = JSON.parse(xhr.responseText);
                                        let items = res.data.items;
                                        for (let i = 0; i < items.length; i++) {
                                            if (items[i].name == good_name) {
                                                let 卡价 = parseFloat(document.getElementById("helper-setting-pageCardPrice").value);
                                                // 获取当前价格
                                                let 当前在售价 = items[i].sell_min_price;
                                                // 求出st求购价
                                                info(`${parseFloat(helper_config.reCalcProfitMargin)}, ${parseFloat(当前在售价)}, ${parseFloat(helper_config.helperCardPrice)}`);
                                                let 反推求购价 = "$"+反推利润公式(
                                                    parseFloat(helper_config.reCalcProfitMargin), parseFloat(当前在售价),
                                                    parseFloat(helper_config.helperCardPrice)
                                                );
                                                当前在售价 = "¥" + 当前在售价;  // 添加货币符号
                                                let 求购价 = items[i].buy_max_price;
                                                求购价 = `<span style="color: ${text_color}">¥` + (求购价*汇率).toFixed(2) + "</span>($" + 求购价 + ")";
                                                let 在售 = items[i].sell_num;
                                                let 求购 = items[i].buy_num;
                                                let buff_order_string = `[BUFF]卡价 ${卡价}，当前在售价 ${当前在售价}，<span style="color: ${text_color}">反推求购价</span> ${反推求购价}，求购价 ${求购价}，<span style="color: ${text_color}">在售</span> ${在售}，<span style="color: ${text_color}">求购</span> ${求购}`;
                                                $(".detail-cont").append(`<div id='buff_order'>${buff_order_string}</div>`);
                                                break;
                                            }
                                        }
                                    }
                                }
                                xhr.open("GET", url, true);
                                xhr.send();
                            })();
                            let steam_order_string = `[STEAM]市场共有${orderList.buy_order_summary}，${orderList.sell_order_summary}`;
                            $(".detail-cont").append(`<div id='steam_order'>${steam_order_string}</div>`);
                            // 修改后的表格字符串
                            let new_buy_order_table = '<table class="market_commodity_orders_table"><tr><th align="right">价格</th><th align="right">数量</th></tr>';
                            let 货币标志 = orderList.price_prefix;
                            // 填充二十个值
                            for (let i = 0; i < orderList.buy_order_graph.length && i < 20; i++) {
                                new_buy_order_table += '<tr>';
                                new_buy_order_table += `<td align="right" class="">${货币标志} ${orderList.buy_order_graph[i][0]}</td>`
                                new_buy_order_table += `<td align="right">${orderList.buy_order_graph[i][1]}</td>`;
                                new_buy_order_table += '</tr>';
                            }
                            // 表格字符串结尾
                            new_buy_order_table += '</table>';
                            // 修改为 新的 buy_order_table
                            orderList.buy_order_table = new_buy_order_table;
                            $(".detail-pic").after(orderList.buy_order_table);    // 添加右侧小表格的代码
                            // let buff_sell_price = data.items[0].price;
                            // $(".market_commodity_orders_header_promote:last").after(`<small class='market_listing_price_with_fee'>${getScale(buff_sell_price, steam_highest_buy_order.cny)}</small>`);   // 客户要求去掉的不必要的比例值
                            // 求购表格
                            $(".market_commodity_orders_table th:first").after("<th>利润率</th>"); // 添加新表头
                            $(".market_commodity_orders_table th:first").after("<th>卖价</th>");
                            $(".market_commodity_orders_table th:last").attr("width", "60px");
                            $(".market_commodity_orders_table td:first").attr("width", "80px");
                            $(".market_commodity_orders_table td:last-child").attr("width", "60px");
                            $(".market_commodity_orders_table tr:last-child").remove();
                            let orderTableList = $(".market_commodity_orders_table tr");
                            let viableScale = 0 // steam订购单比例低于1的数量
                            let 当前反推利润率 = parseFloat(document.getElementById("helper-setting-reCalcProfitMargin").value);
                            // 开始遍历表格
                            for (let i = 1; i < orderTableList.length; i++) {
                                let td = $(orderTableList[i]).find("td:first");
                                let td_count = $(orderTableList[i]).find("td:last");
                                let priceGroup = convertPrice(td.text());
                                // console.log("调试输出priceGroup",priceGroup);

                                // 原本计算比例的逻辑（现在不需要了）
                                // let scale = getScale(buff_sell_price, FtoC(priceGroup[1] + (priceGroup[3] || "00")))
                                // td.after(`<td>${scale}</td>`);
                                
                                // 替换老逻辑 新增利润率这一列的内容
                                // 添加新列的内容
                                let steam的求购价 = priceGroup[0];
                                console.log('buff在售最低价为：', Buff最低出售价人民币, "¥");
                                let 利润率 = 正推利润公式(steam的求购价, Buff最低出售价人民币, 一美金实际成本);
                                // info([steam的求购价, Buff最低出售价, 一美金实际成本, 利润率]);
                                // 写进表格
                                td.after(`<td>${利润率}%</td>`);

                                // 此处应该编写卖价的逻辑（如果st参考货币是人民币的话，先转换为美元）
                                if (g_rgCurrencyData[helper_config.steamCurrency].eCurrencyCode == 23) {
                                    steam的求购价 /= 汇率;
                                }
                                let buff卖价 = 利润率反推卖价(当前反推利润率, steam的求购价, 一美金实际成本);
                                info([buff卖价, 当前反推利润率, steam的求购价, 一美金实际成本]);
                                td.after(`<td>¥ ${buff卖价}</td>`);

                                // 检查steam订购单异常情况，若只有个别比例低于1，提醒用户，排除用于尾部统计的最后一行
                                // if (scale < 1 && i < orderTableList.length - 1) {
                                //     viableScale += parseInt(td_count.text())
                                // }
                            }
                            // 当只有个别比例低于1时，添加提醒
                            switch (true) {
                                case viableScale == 0: break;
                                case viableScale < 3:
                                    $('#steam_order').append(`<div class="warning" style="color: red;"><i class="icon icon_warning_mid" style="filter: invert(1) hue-rotate(120deg)"></i><div class="tips">仅有个别Steam订购单比例低于1，小心卖家自设虚假订购单</div></div>`)
                                    break;
                                case viableScale < 5:
                                    $('#steam_order').append(`<div class="warning" style="color: orange;"><i class="icon icon_warning_mid"></i><div class="tips">比例低于1的Steam订购单过少，请小心购买</div></div>`)
                                    break;
                            }

                            if (helper_config.orderFloatLeft) {
                                $(".market_commodity_orders_table").addClass("order_float_left");
                            }
                        }
                    } else {
                        if ((!secendTry) && orderList.status == "500") {
                            setTimeout(() => {
                                goodsDetailLoadData(data, true);
                            }, 100);
                            return;
                        }
                        $(".detail-cont").append(`<div id='steam_order_error'>${orderList.statusText}</div>`);
                    }
                }
                $(".helper-loading").remove();
                $(".detail-tab-cont th:last").before('<th style="width: 45px;" class="t_Left"><span>比例</span></th>');
                if (steam_lowest_sell_order) {
                    $(".f_Strong .hide-usd")[0].innerText = getWithoutFeePrice(steam_lowest_sell_order.origin, 1);
                } else {
                    $(".f_Strong .hide-usd")[0].innerText = getWithoutFeePrice(steam_price_cny, 1, "CNY");
                }
                for (let i = 0; i < items.length; i++) {
                    let buff_sell_price = items[i].price;
                    // let scale = getScale(buff_sell_price, steam_lowest_sell_order ? steam_lowest_sell_order.cny : steam_price_cny);
                    let 卡价 = document.getElementById("helper-setting-pageCardPrice").value;
                    let scale = (buff_sell_price / (steam_min_price * 卡价)).toFixed(2);
                    if (scale === Infinity) {
                        scale = "∞";
                    }
                    if (!i) {
                        let color;
                        switch (true) {
                            case scale > 0.9: color = "#a0ffc5"; break;
                            case scale > 0.8: color = "#b8ff8a"; break;
                            case scale > 0.74: color = "#fff054"; break;
                            case scale > 0.67: color = "#ff7e15"; break;
                            default: color = "#ff0049"; break;
                        }
                        if (isFirstTime) {
                            $(".steam-link").prop("href", $(".steam-link").prop("href") + "?buffPrice=" + buff_sell_price);
                            $(price_list[isLogined ? 1 : 0]).append($(`<big class='good_scale' style='color:${color};margin-left: 6px'>${scale}</big>`));
                        } else {
                            $(".steam-link").prop("href", $(".steam-link").prop("href").replace(/\d{0,6}[.]?\d{0,2}$/, buff_sell_price));
                            $(".good_scale").text(scale).css("color", color);
                        }
                    }
                    $(price_list[i + (isLogined ? 2 : 1)]).parents("td").after(`<td class="t_Left"><div style="display:table-cell;text-align:center;"><b class="seller_scale">${scale}</b><p class="c_Gray f_12px">${steam_highest_buy_order ? getScale(buff_sell_price, steam_highest_buy_order.cny) : ''}</p></div></td>`);
                }
                daemonThread();
            }
        }

        // 市场目录
        window.buffHelperMarkerListScale = async function (items) {
            // 检测商品是否加载完成
            if ($("#j_list_card>ul>li").length == 0) {
                setTimeout(buffHelperMarkerListScale, 100);
                return;
            }
            
            function hited_text_red_闭包(dom, goodID) {
                return function hited_text_red() {
                    // 本函数用于将点击超链接后，文字变红的效果
                    dom.style.color = 'red';
                    dom.style.fontWeight = '900';

                    // 需要将变红的商品加入浏览器缓存中
                    save_goodID_to_session(goodID);
                }
            }

            // session key is wyscymbhspdid
            function save_goodID_to_session(goodID) {
                // 读取对应商品的id
                // 将id存储到session中
                let goods_id_list = JSON.parse(sessionStorage.getItem('wyscymbhspdid'));
                if (!goods_id_list) {
                    goods_id_list = [];
                }
                goods_id_list.push(goodID);
                goods_id_list = JSON.stringify(goods_id_list);
                sessionStorage.setItem('wyscymbhspdid', goods_id_list);
            }

            function load_goodID_in_session(dom, goodID) {
                // 获取对应商品的id 以及需要被标红的 dom
                // 去session中查找对应商品需不需要被标红
                let goods_id_list = JSON.parse(sessionStorage.getItem('wyscymbhspdid'));
                if (!goods_id_list) {
                    goods_id_list = [];
                }
                // 需要标红时将文字样式设置标红
                if (goods_id_list.includes(goodID)) {
                    dom.style.color = 'red';
                    dom.style.fontWeight = '900';
                }
            }

            // 把先把在售1000+替换为准确的数值
            (function () {
                // 将页面顶部的商品分类也进行强制跳转
                set_top_good_type();
                // 将页面设置价格区间的逻辑也添加上强制跳转
                set_price_range();
                // 保证用户在点击下一页或者底部页面跳转的时候，让页面强制刷新
                set_under_buttom();

                info('页面上的20个商品', items);

                // 页面上的20个商品
                let goods_box = document.querySelector("#j_list_card > ul").children;

                // 遍历所有商品将信息填上
                for (let i = 0; i < goods_box.length; i++) {
                    // 获取单个商品
                    let good = goods_box[i];
                    let good_url = `/goods/${items[i].id}?from=market#tab=selling`;
                    let good_name = items[i].name;
                    let good_icon_url = items[i].goods_info.icon_url;
                    let good_price = split_price(items[i].sell_min_price);
                    let good_sell_num = items[i].sell_num;
                    let good_buy_num = items[i].buy_num;
                    let good_buysellnumText = `${good_buy_num}在求，${good_sell_num}在售，比例${(good_buy_num / good_sell_num).toFixed(2)}`;
                    let good_tag = get_good_tag(good_name);
                    
                    // 设置盒子高度增加一个字体的高度
                    let good_box_height = good.offsetHeight;
                    good.style.height = (good_box_height*1.1) + "px";

                    // 设置图片超链接的指向
                    let good_a = good.querySelector('a');
                    good_a.setAttribute('href', good_url);
                    good_a.setAttribute('title', good_name);
                    good_a.target = '_blank';

                    // 设置商品图片
                    let good_img = good.querySelector('a>img');
                    good_img.setAttribute('src', good_icon_url);
                    good_img.setAttribute('data-original', good_icon_url);

                    // 设置商品文字
                    let good_h3_a = good.querySelector('h3>a');
                    good_h3_a.setAttribute('href', good_url);
                    good_h3_a.setAttribute('title', good_name);
                    good_h3_a.innerText = good_name;
                    good_h3_a.target = '_blank';
                    good_a.addEventListener('click', hited_text_red_闭包(good_h3_a, items[i].id));
                    good_h3_a.addEventListener('click', hited_text_red_闭包(good_h3_a, items[i].id));
                    load_goodID_in_session(good_h3_a, items[i].id);

                    // 设置商品价格
                    let good_strong = good.querySelector('p>strong');
                    if (good_price.float == "") good_strong.innerHTML = `¥ ${good_price.int}`;
                    else                        good_strong.innerHTML = `¥ ${good_price.int}<small>${good_price.float}</small>`;

                    // 设置在售数量
                    let good_p_span = good.querySelector('p>span');
                    good_p_span.innerText = good_buysellnumText;

                    // 设置品质
                    let good_span = good.querySelector('span.tag');
                    if (good_span) {
                        good_span.innerText = good_tag;
                        good_span.className = `tag ${tag_class[good_tag]}`
                    }

                    // 设置每件商品的价差率
                    let good_price_diff_parent = good.children[0];
                    let good_price_diff = document.createElement("span");
                    let buy_max_price = parseFloat(items[i].buy_max_price);
                    let sell_min_price = parseFloat(items[i].sell_min_price);
                    let 价差率 = ((sell_min_price - buy_max_price) / sell_min_price * 100).toFixed(2) + '%';
                    let tmp_string = "价差率：" + 价差率;
                    good_price_diff.className = "price-scale-box";
                    good_price_diff.innerText = tmp_string;
                    good_price_diff_parent.appendChild(good_price_diff);
                }

                // 本函数用于在我们点击下一页的时候，保证刷新了页面，让商品在售数量1000+可以保证刷新到位
                function set_under_buttom() {
                    if (!document.querySelector("#j_market_card > div.pager.card-pager.light-theme.simple-pagination > ul")) {
                        info(`[function error] in set_under_button (document.querySelector("#j_market_card > div.pager.card-pager.light-theme.simple-pagination > ul")) 无效`);
                        return ;
                    }
                    console.log('in set_under_buttom');
                    let ul = document.querySelector("#j_market_card > div.pager.card-pager.light-theme.simple-pagination > ul").children;
                    for (let i = 0; i < ul.length; i++) {
                        let page_num = "";
                        if (ul[i].className != "") continue;
                        if (ul[i].innerText == "上一页") {
                            page_num = (+document.querySelector("#j_market_card > div.pager.card-pager.light-theme.simple-pagination > ul > li.active").innerText) - 1;
                        } else if (ul[i].innerText == "下一页") {
                            page_num = (+document.querySelector("#j_market_card > div.pager.card-pager.light-theme.simple-pagination > ul > li.active").innerText) + 1;
                        } else {
                            page_num = ul[i].innerText;
                        }
                        let old_url = document.URL;
                        let args = get_url_args(old_url);
                        args = flush_page_num(args, page_num);
                        let url = `https://buff.163.com/market/csgo#` + join_args(args);
                        ul[i].addEventListener('click', function (e) {
                            // window.location.href = url;
                            // window.location.replace(url);
                            // document.write(`<meta http-equiv="refresh" content="0; url=${url}">`);
                            // 这里强制页面跳转有点小bug，后续有时间再修吧，总之现在可以正常跳转了
                            document.write(`<script>window.location.href = "${url}"; window.location.reload();</script>`);
                            console.log('set:'+url);
                        });
                    }
                };

                // 获取URL参数
                function get_url_args(url) {
                    let idx = url.indexOf('#');
                    let args = "";
                    if (idx == -1) {
                        args = [['game','csgo'], ['page_num', '1'], ['tab','selling']];
                    } else {
                        args = url.substring(idx+1).split('&');
                        for (let i = 0; i < args.length; i++) {
                            args[i] = args[i].split('=');
                        }
                    }
                    return args;
                }

                // 刷新页码
                function flush_page_num(args, page_num) {
                    let flag = 0;
                    for (let i = 0; i < args.length; i++) {
                        if (args[i][0] == 'page_num') {
                            args[i][1] = ""+page_num;
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 0) {
                        args.splice(1, 0, ['page_num', ""+page_num]);
                    }
                    return args;
                }

                // 将参数数组转换为字符串传递回URL
                function join_args(args) {
                    for (let i = 0; i < args.length; i++) {
                        args[i] = args[i].join('=');
                    }
                    let res = args.join('&');
                    return res;
                }

                // 将页面设置价格区间的逻辑也添加上强制跳转
                function set_price_range() {
                    if (!document.querySelector("#j_counter > div.w-Counter-pannel > a.i_Btn.i_Btn_main.i_Btn_small")) {
                        setTimeout(set_price_range, 300);
                        return ;
                    }
                    // 设置监听事件
                    let btn = document.querySelector("#j_counter > div.w-Counter-pannel > a.i_Btn.i_Btn_main.i_Btn_small");
                    btn.addEventListener('click', function (e) {
                        // 获取当前的URL参数
                        let old_url = document.URL;
                        let args = get_url_args(old_url);
                        // 加上最大最小价格
                        args = set_MinAndMax_price(args);
                        // 构造新的URL
                        let url = `https://buff.163.com/market/csgo#` + join_args(args);
                        // 进行页面跳转
                        document.write(`<script>window.location.href = "${url}"; window.location.reload();</script>`);
                        console.log('set:'+url);
                    });
                }

                // 加上最大最小价格
                function set_MinAndMax_price(args) {
                    let min_input = document.querySelector("#j_counter > div.w-Counter-input.w-Counter-input3 > input:nth-child(1)");
                    let max_input = document.querySelector("#j_counter > div.w-Counter-input.w-Counter-input3 > input:nth-child(2)");
                    if (!min_input || !max_input) {
                        info(`[function error] in set_MinAndMax_price (最大最小价格输入框不存在)`);
                        return ;
                    }
                    // 最大最小值的标志位
                    let minPriceFlag = 0;
                    let maxPriceFlag = 0;
                    let minPrice;
                    let maxPrice;
                    // 获取最小价格 和 最大价格
                    if (min_input.value != "") {
                        minPrice = min_input.value;
                    } else {
                        minPriceFlag = 1;
                    }
                    if (max_input.value != "") {
                        maxPrice = max_input.value;
                    } else {
                        maxPriceFlag = 1;
                    }
                    // 判断URL中是否含有最大最小价格并替换
                    for (let i = 0; i < args.length; i++) {
                        if (minPriceFlag && maxPriceFlag) {
                            break;
                        }
                        if (args[i][0] == 'min_price') {
                            args[i][1] = minPrice;
                            minPriceFlag = 1;
                        } else if (args[i][0] == 'max_price') {
                            args[i][1] = maxPrice;
                            maxPriceFlag = 1;
                        }
                    }
                    // 如果没找到最小价格则主动添加
                    if (minPriceFlag == 0) {
                        args.splice(1, 0, ['min_price', minPrice]);
                    }
                    // 如果没找到最大价格则主动添加
                    if (maxPriceFlag == 0) {
                        args.splice(1, 0, ['max_price', maxPrice]);
                    }
                    return args;
                }

                // 本函数的作用是当点击了对应的商品类型时，强制刷新页面
                function set_top_good_type() {
                    info('in set_top_good_type');
                    let all_div = document.querySelector("body > div.market-list > div.l_Layout > div.market-header.black > div.h1z1-selType.type_csgo");
                    for (let i = 0; i < all_div.children.length; i++) {
                        let child = all_div.children[i];
                        // 添加商品大类的跳转
                        child.addEventListener('click', function (e) {
                            e.preventDefault();
                            // let good_type = child.querySelector('p').value;
                            let good_type = child.querySelector('p').getAttribute('value');
                            let jmp_url = 'https://buff.163.com/market/csgo#game=csgo&page_num=1&category_group=' + good_type + '&tab=selling';
                            // let a = document.createElement('a');
                            // a.href = jmp_url;
                            // a.click();
                            document.write(`<script>window.location.href = "${jmp_url}"; window.location.reload();</script>`);
                            console.log('set:'+jmp_url);
                        });
                        // 添加商品细分类的跳转
                        let Subclassification = child.querySelector('ul').children;
                        for (let i = 0; i < Subclassification.length; i++) {
                            Subclassification[i].addEventListener('click', function (e) {
                                e.preventDefault();
                                // let good_type = Subclassification[i].value;
                                let good_type = Subclassification[i].getAttribute('value');
                                info('in set_top_good_subtype'+good_type);
                                let jmp_url = 'https://buff.163.com/market/csgo#game=csgo&page_num=1&category=' + good_type + '&tab=selling';
                                // let a = document.createElement('a');
                                // a.href = jmp_url;
                                // a.click();
                                document.write(`<script>window.location.href = "${jmp_url}"; window.location.reload();</script>`);
                                console.log('set:'+jmp_url);
                            });
                        }
                    }
                }

                // 本函数的作用是当点击了对应的商品类型时，强制刷新页面（本函数先不做）
                function set_line_good_type() {
                    console.log('in set_line_good_type');
                    let all_div = document.querySelectorAll("body > div.market-list > div.l_Layout > div.market-header.black > div.criteria > div[id]");
                    for (let i = 0; i < all_div.length; i++) {
                        let child = all_div[i].querySelectorAll('.colored_tag');
                        for (let j = 0; j < child.length; j++) {
                            child[i].addEventListener('click', function (e) {
                                e.preventDefault();
                                setTimeout(100, location.reload());
                            })
                        }
                    }
                }

                // 本函数用于分隔小数点前的整数部分以及小数部分
                function split_price(price) {
                    if (price.includes('.')) {
                        let idx = price.indexOf('.');
                        return {"int": price.substring(0, idx), "float": price.substring(idx)};
                    } else {
                        return {"int": price, "float": ""}
                    }
                }

                // 本函数用户获取商品的品质
                function get_good_tag(name) {
                    let l_idx = name.indexOf('(');
                    let r_idx = name.indexOf(')');
                    return name.substring(l_idx+1, r_idx);
                }
            })();

            $(".list_card li>p>span.l_Right").removeClass("l_Right").addClass("l_Left");
            let randomID = Math.round(Math.random() * 1000);
            let goods = $("#j_list_card>ul>li");
            itemNum = items.length;

            // 根据反推利润率计算出 st求购价并显示（先不添加在此处，此处代码移动至init函数内部）

            // 添加进度条
            $(".tab>li.on").append("<i id=helper-loading-" + randomID + " class=\"icon icon_uploading helper-loading\"></i>");
            $(".market-list .blank20:last").prepend('<div id=helper-progress-bar-' + randomID + ' class="helper-progress-bar"></div>');
            for (let i = 0; i < goods.length; i++) {
                $(goods[i]).attr("data-default-sort", i);
                if (items[i].sell_num == 0) {
                    updateProgressBar(randomID);
                    continue;
                }
                await marketListLoadData(items[i], goods[i], randomID);
            }

            async function marketListLoadData(item, good, randomID, secendTry) {
                let target = $(good).find("p>strong.f_Strong")[0];
                let buff_item_id = item.id;                                     // buff商品ID
                let buff_buy_num = item.buy_num;                                // buff求购数量
                let buff_buy_max_price = item.buy_max_price;                    // buff求购最高价
                let buff_sell_num = item.sell_num;                              // buff在售数量
                let buff_sell_min_price = item.sell_min_price;                  // buff出售最低价
                let buff_sell_min_price_CNY = item.sell_min_price;              // buff出售最低价（人民币）
                //这里将id和buff以key-value的形式添加到全局对象(默认为美元)
                bidPrice[buff_item_id]=buff_sell_min_price*exchangeRate.CtoF;
                //这里将id+CNY和buff以key-value的形式添加到全局对象(为人民币)
                bidPrice[buff_item_id+"CNY"]=buff_sell_min_price_CNY;
                info(`buff_sell_min_price_CNY${buff_sell_min_price_CNY}`);
                GM_setValue("bidPrice",bidPrice);
                // console.log("BUFF出售最低价(人民币)：",buff_sell_min_price);
                // console.log("BUFF出售最低价(美元)：",buff_sell_min_price*exchangeRate.CtoF);
                // console.log("bidPrice对象",bidPrice);
                // console.log("购买100美元充值卡实际成本(人民币)：",helper_config.cardPrice);
                // console.log("购买100美元充值卡实际成本(美元)：",helper_config.cardPrice*exchangeRate.CtoF);
                let steam_price_cny = item.goods_info.steam_price_cny * 100;    // buff提供的steam国区售价
                let steam_market_url = item.steam_market_url;                   // steam市场链接
                let buff_sell_reference_price = item.sell_reference_price;      // buff出售参考价(没卵用)
                let steam_highest_buy_order = undefined;                        // 不能使用全局变量，不然未成功加载的数据比例会错误
                let steam_lowest_sell_order = undefined;                        // 不能使用全局变量，不然未成功加载的数据比例会错误
                $(good).attr("data-order-sort", Infinity);
                $(good).attr("data-sold_number-sort", Infinity);
                if (helper_config.buffSellThreshold >= buff_sell_num) {
                    $(good).attr("data-buff-sort", Infinity);
                    $(target).after($(HIGHLIGHT_TEMPLATE).text("已忽略"));
                } else {
                    let orderList = await getSteamOrderList(buff_item_id, steam_market_url);
                    if (orderList.success) {
                        steam_highest_buy_order = orderList.highest_buy_order && {
                            origin: orderList.highest_buy_order,
                            cny: FtoC(orderList.highest_buy_order)
                        };
                        steam_lowest_sell_order = orderList.lowest_sell_order && {
                            origin: orderList.lowest_sell_order,
                            cny: FtoC(orderList.lowest_sell_order)
                        };
                        // 没有有效的订购单
                        if (orderList.buy_order_table == "") {
                            $(target).after($(INFO_TEMPLATE).text("没有有效订购单"));
                        } else {
                            let steamOrderScale = getScale(buff_sell_min_price, steam_highest_buy_order.cny);
                            if (helper_config.displaySoldNumber) {
                                let soldNumber = await getSteamSoldNumber(item.appid, item.market_hash_name);
                                if (soldNumber.success) {
                                    soldNumber.volume = soldNumber.volume.replace(",", "");
                                    $(good).attr("data-sold_number-sort", soldNumber.volume || 0);
                                    $(target).after($(STEAM_SOLD_NUMBER_TEMPLATE).text((soldNumber.volume || 0) + "┊"));
                                } else {
                                    let text = soldNumber.statusTextShort;
                                    $(target).after($(STEAM_SOLD_NUMBER_TEMPLATE).text((text ? text : "错误") + "┊"));
                                }
                            } else {
                                let orderNumber = $(orderList.buy_order_summary)[0].innerText;
                                $(good).attr("data-order-sort", steamOrderScale);
                                // $(target).after($(STEAM_ORDER_NUMBER_TEMPLATE).text(orderNumber + "┊"));     // 貌似是不需要的行为
                            }
                            // paintingGradient(steamOrderScale, target, 4, STEAM_ORDER_SCALE_TEMPLATE);        // 貌似是不需要的行为
                        }
                    } else {
                        if ((!secendTry) && orderList.status == 500) {
                            setTimeout(() => {
                                marketListLoadData(item, good, randomID, true);
                            }, 100);
                            return;
                        }
                        $(target).after($(ERROR_TEMPLATE).text(orderList.statusText.split("，")[0]));
                    }
                    let withoutFeePrice = getWithoutFeePrice(steam_lowest_sell_order ? steam_lowest_sell_order.origin : steam_price_cny);
                    // let scale = getScale(buff_sell_min_price, steam_lowest_sell_order ? steam_lowest_sell_order.cny : steam_price_cny);    // 原有的计算比例的公式 现修改为新公式
                    let steam_min_price = orderList.buy_order_graph[0][0] ? orderList.buy_order_graph[0][0] : "频繁访问steam";
                    let 卡价 = document.getElementById("helper-setting-pageCardPrice").value;
                    let scale = 0;
                    if (steam_min_price != "频繁访问steam") {
                        scale = (buff_sell_min_price / (steam_min_price * 卡价)).toFixed(2);
                    } else {
                        scale = "频繁访问steam";
                    }
                    $(good).attr("data-buff-sort", scale);
                    $(target).prepend(`<span>${target.childNodes[0].textContent}</span>`);
                    target.childNodes[1].remove();
                    // $(target).append($("<span class=\"f_12px f_Bold c_Gray\"></span>").css("margin-left", "5px").text(withoutFeePrice));   // 市场页面在售最低价的右侧小黑数字
                    // $(target).append($("<span class=\"f_12px f_Bold c_Gray\"></span>").css("margin-left", "5px").text(withoutFeePrice));   // 市场页面在售最低价的右侧小黑数字
                    $(target).append($("<span class=\"f_12px f_Bold c_Gray\"></span>").css("margin-left", "5px").text('¥' + buff_buy_max_price));   // 市场页面在售最低价的右侧小黑数字

                    // 过于频繁访问steam导致无法返回数据
                    if (scale != "频繁访问steam") {
                        paintingGradient(scale, target, 3);  // 添加比例的代码（应该修改为 buff卖价 除以 steam求购价*卡价 的值）
                    } else {
                        // 往页面写入 "频繁访问steam"
                        $(target).append($('<strong class="f_16px f_Strong price_scale l_Right"></strong>').css("color", "rgb(255,0,0)").text(scale));
                    }

                    withoutFeePrice = target.children[target.children.length - 2];
                    scale = target.children[target.children.length - 1];
                    let strWidth = 5;
                    for (let i = 0; i < target.children.length; i++) {
                        strWidth += target.children[i].offsetWidth;
                    }
                    let displayPrice = $(target).text().match(/([€₽\$¥]\s)((\d+)(\.\d{1,2})?)/) || [""];
                    let tryMe = 0;
                    while (strWidth >= 192) {
                        switch (tryMe++) {
                            // 超长以后显示的越少越好，所以不用toFixed以免出现小数是0的情况
                            case 0:     // 0/1
                                withoutFeePrice.innerText = Math.round(withoutFeePrice.innerText * 10) / 10;
                                break;
                            case 1:     // 0/2
                                withoutFeePrice.innerText = Math.round(withoutFeePrice.innerText);
                                break;
                            case 2:     // 0/1
                                scale.innerText = Math.round(scale.innerText * 10) / 10;
                                break;
                            case 3:     // 0/3
                                let text = displayPrice[1] + Math.ceil(displayPrice[2]);    // 价格抹零
                                $(target).text(text);
                                displayPrice = text.match(/([€₽\$¥]\s)((\d+)(\.\d{1,2})?)/);
                                break;
                            case 4:     // 0/2
                                scale.innerText = Math.ceil(scale.innerText);
                                break;
                            case 5:     // no one's gonna know
                                // $(target).text((+displayPrice[3]).toString(16));
                                // withoutFeePrice.innerText = withoutFeePrice.innerText.toString(16);
                                withoutFeePrice.innerText = "";
                                strWidth = 0;
                                continue;
                        }
                        strWidth = 5;
                        for (let i = 0; i < target.children.length; i++) {
                            strWidth += target.children[i].offsetWidth;
                        }
                    }
                }
                if (needSort && (helper_config.sortAfterAllDone ? itemCount == itemNum - 1 : true)) {
                    let arr = needSort.split("_");
                    sortGoods("data-" + arr[0], arr[1] == "asc");
                }
                updateProgressBar(randomID);
            }
        }

        // 检视增强模组
        window.buffHelperModule_inspestEnhancementCsgo = function (data) {
            // 检测商品是否加载完成
            if ($("#market-selling-list").length == 0) {
                setTimeout(buffHelperModule_inspestEnhancementCsgo, 100);
                return;
            }
            if ($("#market-selling-list").hasClass("buffed")) { return; }
            $("#market-selling-list").addClass("buffed");
            // 不支持微信时给个占位图标
            let alipayIcon = $(".icon_payment_alipay");
            for (let i = 0; i < alipayIcon.length; i++) {
                let element = alipayIcon[i];
                if (!element.nextElementSibling) {
                    $(element).after('<i class="icon icon_select_wx_small" style="opacity:0;" title="Support BUFF Balances-bank card"></i>');
                }
            }
            // 支付图标移动到购买按钮下
            let paymentIcon = $(".icon_payment_alipay,.icon_payment_others").parent();
            paymentIcon.addClass("paymentIcon on");
            $(".paymentIcon .icon_payment_alipay").addClass("icon_select_alipay_small").removeClass("icon_payment_alipay");
            $(".paymentIcon .icon_payment_others").addClass("icon_select_wx_small").removeClass("icon_payment_others");
            for (let i = 0; i < paymentIcon.length; i++) {
                const element = paymentIcon[i];
                $(element).parent().next().append(element);
            }
            // 检测是否支持这个类型/游戏的饰品
            let goods_id = getGoodsId();
            if (data.goods_infos[goods_id].appid != 730 || ENHANCEMENT_SUPPORT_LIST.indexOf(data.goods_infos[goods_id].tags.category_group.internal_name) < 0) { return; }
            // 英文页面标志
            let isEn = $("#j_lang-switcher").data("current") === "en";
            // 整体CSS
            $(".list_tb_csgo>tr>th.t_Left")[0].style.width = "550px";
            // 给检视按钮去掉点击属性，防止产生图片无法关闭的bug
            $(".csgo_inspect_img_btn").attr("disabled", true).css({
                "pointer-events": "none"
            });
            // 给饰品图片加入点击属性用于检视
            $(".pic-cont.item-detail-img").click(function () {
                this.children[1].click();
            }).mouseenter(function () {
                $(this).css("background", $(this.children[1]).css("background"));
            }).mouseleave(function () {
                $(this).css("background", "");
            }).css({
                "cursor": "pointer"
            });
            // 拿到每个饰品对应的dom
            let skin_list = $(".list_tb_csgo").find("[id^='sell_order_']");
            for (let i = 0; i < skin_list.length; i++) {
                let mom = skin_list[i];
                // 贴纸移动到图片dom中（保证垂直居中）
                let sticker = $(mom).find(".csgo_sticker");
                $(sticker).addClass("sticker_parent_div");
                $(mom).find("td:nth-child(2)").prepend(sticker);
                getItemDetail(mom);
            }
            // 渐变/淬火等特殊皮肤的tag
            let stags = $(".stag");
            for (let i = 0; i < stags.length; i++) {
                let stag = $(stags[i]);
                stag.prev().append(stag);
            }
            // 贴纸大图
            let stickers = $(".stickers");
            for (let i = 0; i < stickers.length; i++) {
                let element = stickers[i];
                element.innerHTML += "<span class='tooltiptext'>" + element.innerHTML + "</span>";
            }
            $("span.f_12px.c_Gray:contains('%')").css("margin-left", "6px");
            stickers.addClass("tooltip");
            // 贴纸遮盖
            stickers = $(".stickers.masked");
            let min = 0.3;
            for (let i = 0; i < stickers.length; i++) {
                let float = parseInt(stickers[i].nextElementSibling.innerText);
                $(stickers[i]).css("opacity", float * (1 - min) / 100 + min);
            }
            $(".stickers.masked").removeClass("masked");
            // 贴纸顺序
            if (helper_config.reverseSticker) {
                $(".sticker-cont").css("float", "right");
            }
            // 英文页面3D检视
            if (isEn) {
                $(".ctag.btn_3d").html($(".ctag.btn_3d").html().substr(0, 37));
            }

            function getItemDetail(parent, secondTime) {
                if ($(parent).find(".textOne")[0]) { return; }
                // 拿到每个饰品的图片对象
                let skin = $(parent).find(".item-detail-img")[0];
                // 获取饰品对应的信息并加载进data
                let classid = $(skin).data("classid");
                let instanceid = $(skin).data("instanceid");
                let sell_order_id = $(skin).data("orderid");
                let origin = $(skin).data("origin");
                let assetid = $(skin).data("assetid");
                let data = {
                    appid: 730,
                    game: "csgo",
                    classid: classid,
                    instanceid: instanceid,
                    sell_order_id: sell_order_id,
                    origin: origin,
                    assetid: assetid
                };
                // 发送异步请求获取饰品详情
                $.ajax({
                    url: "/market/item_detail",
                    method: "get",
                    timeout: ajaxTimeout,
                    data: data,
                    success: function (data) {
                        let result = $(data)[0];
                        // 获取待添加种子的dom对象
                        let origin_float = $(parent).find(".wear-value")[0];
                        try {
                            let seed = "<div class='wear-value'>图案模板(seed):&nbsp;<b style='color:crimson'>" + $(result).find(".skin-info>p:first").text().match(/\d{1,}/)[0] + "</b></div>";
                            $(origin_float).before(seed);
                        } catch (error) {
                            if (secondTime) {
                                $(origin_float).before("<div class='wear-value'><b style='color:crimson'>获取失败，请稍后再试</b></div>");
                                return;
                            } else {
                                setTimeout(getItemDetail(parent, true), 500);
                            }
                        }
                        // 获取名称标签对象
                        let name = $(result).find("p.name_tag")[0];
                        if (name) {
                            // 设定名称标签的样式
                            $(name).css({
                                "background": "transparent",
                                "padding": "0"
                            });
                            // 获取待添加名称标签的对象并添加名称标签
                            let targ_name = $(parent).find(".csgo_value")[0];
                            $(targ_name).before(name);
                        }
                        // 截取皮肤磨损并加粗
                        origin_float.innerHTML = "磨损: <b>" + origin_float.innerText.match(/0[.]\d*/)[0] + "</b>";
                        // 获取排名对象
                        let rank = $(result).find(".skin-info>.des")[0];
                        if (rank) {
                            // 位置在种子后面
                            $(parent).find(".csgo_value>.wear-value:first").append("<span style='margin-left:10px'>磨损排名:&nbsp;<b class='float_rank'>" + rank.innerText.match(/\d{1,}/)[0] + "</b></span>");
                            // 位置在磨损后面
                            // $(origin_float).html(origin_float.innerHTML + "<i class='float_rank'>「#<b>" + rank.innerText.match(/\d{1,}/)[0] + "</b>」</i>");
                        }
                    },
                    error: function (msg) {
                        if (msg.status == 429) {
                            msg.statusText = "请求太频繁";
                        }
                        console.log("error:", msg);
                        let origin_float = $(parent).find(".wear-value")[0];
                        $(origin_float).before("<div class='wear-value'><b style='color:crimson'>" + msg.statusText + "</b></div>");
                    }
                });
            }

        };

        function initHelper() {
            // 确认侧边浮动工具栏是否存在
            if ($(".floatbar>ul").length == 0) {
                setTimeout(() => { initHelper(); }, 100);
                return;
            }
            // 确认下一页的按钮不在
            if ($("#buff_tool_nextpage").length != 0) { return; }
            // 读取本地存储的值（读不到时执行该代码块）
            if (!GM_getValue("helper_alert_first")) {
                // 此代码块仅仅是一个小弹窗告知用户此脚本是第一次安装
                $("body").append('<div id="j_w-Toast" class="w-Toast_warning" style="display: block; margin-left: -195px; margin-top: -35px;"><p><i class="icon icon_warning_mid"></i>你应该是第一次安装“网易BUFF价格比例(找挂刀)插件” 本插件完全免费，让你付费购买的都是骗子。请熟知。</p> <div> <a href="javascript:void(0)" class="agreementsBtn i_Btn i_Btn_mid i_Btn_D_red" style="margin-top: 15px;">我已知晓<span class="agreementsCountDown" style="margin-left:10px">5</span></a></div></div>');
                let count = 5;
                let countDown = setInterval(function () {
                    if (--count == 0) {
                        clearInterval(countDown);
                        $(".agreementsCountDown").remove();
                    } else {
                        $(".agreementsCountDown").text(count);
                    }
                }, 1000);
                $(".agreementsBtn").click(function () {
                    if (!count) {
                        GM_setValue("helper_alert_first", true);
                        $("#j_w-Toast").hide("normal", () => {
                            $("#j_w-Toast").remove();
                        });
                    } else {
                        alert("认真看一会，还有" + count + "秒就可以点了");
                    }
                });
            }
            // 添加设置按钮
            $(".floatbar>ul").prepend("<li><a id='buff_tool_setting'><i class='icon icon_menu_setting'></i><p>设置</p></a></li>");
            $("#buff_tool_setting").click(function () {
                openSettingPanel();   // 打开设置页面
            }).parent().css("cursor", "pointer");
            // 添加加大版下一页按钮
            $(".floatbar>ul").prepend("<li><a id='buff_tool_nextpage'><i class='icon icon_slide_right2' style='height: 40px;width: 39px;'></i><p>下一页</p></a></li>");
            $("#buff_tool_nextpage").click(function () {
                //下一页就清空bidPrice，为了效率
                bidPrice={};
                // $(".page-link.next").click();
                // 下一页应该强制刷新
                (function () {
                    let page_num = (+document.querySelector("#j_market_card > div.pager.card-pager.light-theme.simple-pagination > ul > li.active").innerText) + 1;
                    let url = `https://buff.163.com/market/csgo#game=csgo&page_num=${page_num}&tab=selling`;
                    document.write(`<script>window.location.href = "${url}"; window.location.reload();</script>`);
                })();
                $("#sort_scale").removeClass();
            }).parent().css("cursor", "pointer");
            // 初始化设置页面
            $("#helper-version").text($("#helper-version").text() + GM_info.script.version);
            $("#helper-setting-checkBtn").click(() => { checkSteamConnection() });
            $("#helper-setting-resetAll").click(() => { resetConfig(); });
            $(".helper-setting-shadow").click(function (e) {
                if (e.target == this) {
                    $(this).fadeOut();
                }
            });
            // 添加设置页面操作
            $(".helper-setting").change(function (e) {
                let target = e.target;
                let optionTarget = target.dataset.optionTarget;
                let val = target.getAttribute("value") ? target.getAttribute("value") : target.value;
                // 不知道什么玄学，只有添加了这个if才可以解决设置页面里面的卡价数值读取错误的bug
                let loadValuebuglist = ["helper-setting-pageCardPrice", "helper-setting-reCalcProfitMargin"];
                // if (target.id == "helper-setting-pageCardPrice" || target.id == "helper-setting-reCalcProfitMargin") {
                if (loadValuebuglist.includes(target.id)) {
                    val = parseFloat(target.value);
                }
                helper_config[optionTarget] = val;
                // info(`in 设置页面被修改 ${optionTarget}: ${val}`);
                // info(`${helper_config[optionTarget]}`);
                if (optionTarget == "steamCurrency" && g_rgCurrencyData[val].eCurrencyCode != 23) {
                    let toast = showMessage(`正在获取${val}的汇率`, "访问时间取决于steam访问速度，期间请不要关闭页面", "info", 20000);
                    updateRate(1, toast);
                } else {
                    console.log(helper_config);
                    GM_setValue("helper_config", helper_config);
                }
                init();
            });
            // // 添加反推利润率修改的方法
            // document.getElementById("helper-setting-reCalcProfitMargin").oninput = function() {
            //     let 反推利润率 = document.getElementById("helper-setting-reCalcProfitMargin").value;
            //     helper_config[reCalcProfitMargin] = 反推利润率;

            //     // 显示所有的st求购价
            //     show_st_buymoney();
                            
            // }
            // 注册管理工具菜单
            GM_registerMenuCommand('打开设置面板', () => {
                openSettingPanel();
            });
            GM_registerMenuCommand('插件官网', () => {
                window.open("https://greasyfork.org/zh-CN/scripts/410137");
            });
            // 初始化设置页面后填装面板
            init();
        }

        // 按下右侧浮动工具栏的设置按钮时调用的函数
        function openSettingPanel() {
            updateSteamStatus();
            $(".helper-setting-shadow").css({
                "opacity": 0,
                "display": "flex"
            }).animate({ opacity: '1' }, 300);
        }

        function loadConfig() {
            // 使用 GM_getValue 读取浏览器中的 helper_config 值
            let config = GM_getValue("helper_config");
            if (config && Object.keys(config).length) {
                // 旧版更新到新版导致无数据
                config.pageSize = config.pageSize ? config.pageSize : 20;
                return config;
            }
            return clone(DEFAULT_CONFIG);
        }

        function resetConfig() {
            GM_setValue("helper_config", null);
            GM_setValue("exchangeRate", null);
            GM_setValue("top_bookmarked-warning", null);
            helper_config = clone(DEFAULT_CONFIG);
            init();
            showMessage("重置成功", "插件已恢复初始设定", "info", 2000);
        }

        function initCurrency() {
            for (let key in g_rgCurrencyData) {
                $(".steam-currency-selector").append("<li value=" + g_rgCurrencyData[key].strCode + ">" + g_rgCurrencyData[key].strCode + "（" + g_rgCurrencyData[key].strSymbol + "）</li>");
            }
            syncCurrency();
            if (steamCurrency.eCurrencyCode != 23) {
                updateRate();
            }
        }

        function init() {
            $(".helper-setting>.list_tb .on").removeClass("on");

            if (helper_config.currencyEffectCalculate) {
                $("#helper-setting-currencyEffectCalculate").attr("value", helper_config.currencyEffectCalculate).children(":first").addClass("on");
            }
            if (helper_config.overrideSortRule) {
                $("#helper-setting-stickerSort").attr("value", helper_config.overrideSortRule).children(":first").addClass("on");
            }
            if (helper_config.sortAfterAllDone) {
                $("#helper-setting-sortAfterAllDone").attr("value", helper_config.sortAfterAllDone).children(":first").addClass("on");
            }
            if (helper_config.orderFloatLeft) {
                $("#helper-setting-orderFloatLeft").attr("value", helper_config.orderFloatLeft).children(":first").addClass("on");
                $(".market_commodity_orders_table").addClass("order_float_left");
            } else {
                $(".market_commodity_orders_table").removeClass("order_float_left");
            }
            if (helper_config.reverseSticker) {
                $("#helper-setting-reverseSticker").attr("value", helper_config.reverseSticker).children(":first").addClass("on");
            }
            if (helper_config.helperCardPrice) {
                // 设置 设置页面卡价 的值
                $("#helper-setting-pageCardPrice").attr("value", helper_config.helperCardPrice).children(":first").addClass("on");
                // 刷新网页所有商品的st反推求购价
                show_st_buymoney();
            }
            if (helper_config.reCalcProfitMargin) {
                // 设置反推利润率的值
                $("#helper-setting-reCalcProfitMargin").attr("value", helper_config.reCalcProfitMargin).children(":first").addClass("on");
                // 刷新网页所有商品的st反推求购价
                show_st_buymoney();
            }
            reverseStickers(helper_config.reverseSticker);
            syncSort();
            $("#helper-setting-pageSize").val(helper_config.pageSize);
            $("#helper-setting-cardPrice").val(helper_config.cardPrice);
            $("#helper-setting-buffSellThreshold").val(helper_config.buffSellThreshold);
            $("#helper-setting-maxRange").val(helper_config.maxRange);
            $("#helper-setting-minRange").val(helper_config.minRange);
            $("#helper-setting-marketColorLow").val(helper_config.marketColorLow);
            $("#helper-setting-marketColorHigh").val(helper_config.marketColorHigh);
            updateSteamStatus();
            syncCurrency();
            parseColor();
        }

        function initSortBtn() {
            $(".block-header>.l_Right").append($('<div class="w-Select-Multi w-Select-scroll buff-helper-sort" style="visibility: visible; width: 140px;"><h3 id="helper-sort-text">比例排序</h3><i class="icon icon_drop"></i><ul style="width: 140px;"><li data-value="null">默认</li><li data-value="buff-sort_asc"><span class="w-Order_asc">buff比例从低到高<i class="icon icon_order"></i></span></li><li data-value="buff-sort_desc"><span class="w-Order_des">buff比例从高到低<i class="icon icon_order"></i></span></li><li data-value="order-sort_asc"><span class="w-Order_asc">求购比例从低到高<i class="icon icon_order"></i></span></li><li data-value="order-sort_desc"><span class="w-Order_des">求购比例从高到低<i class="icon icon_order"></i></span></li></ul></div>'));
            var sortBtnTimeout;
            $(".buff-helper-sort").click(function () {
                $(this).addClass("on");
                clearTimeout(sortBtnTimeout);
            }).mouseleave(function () {
                let t = $(this);
                if (t.hasClass("on")) {
                    sortBtnTimeout = setTimeout(() => t.removeClass("on"), 300);
                }
            });
            $(".buff-helper-sort li").click(function (e) {
                e.stopPropagation();
                needSort = this.dataset.value;
                if (this.dataset.value == "null") {
                    $("#helper-sort-text").text("比例排序");
                    sortGoods("data-default-sort", true);
                } else {
                    $("#helper-sort-text").text(this.innerText);
                    let arr = this.dataset.value.split("_");
                    sortGoods("data-" + arr[0], arr[1] == "asc");
                }
                $(".buff-helper-sort").removeClass("on");
            });
            syncSort();
            setTimeout(() => {
                // 修改buff排序时重置比例排序规则
                $("div[name='sort_by']").change(function () {
                    if (helper_config.overrideSortRule && this.getAttribute("value")) {
                        needSort = this.dataset.value;
                        $("#helper-sort-text").text("默认");
                    }
                });
            }, 500);
        }

        function syncSort() {
            needSort = helper_config.needSort;
            $("#helper-setting-sortRule>h3").text($("#helper-setting-sortRule li[value=" + helper_config.needSort + "]").addClass("on").text());
            $("#helper-sort-text").text($(".buff-helper-sort li[data-value=" + helper_config.needSort + "]").click().text());
        }

        function reverseStickers(isLeft) {
            $(".sticker-cont").css("float", isLeft ? "right" : "left"); // 没写错
        }

        function updateSteamStatus() {
            if (steamConnection === undefined) {
            } else if (steamConnection) {
                if (!$(".helper-setting-steamConnection>.c_Green").text()) {
                    $(".helper-setting-steamConnection").html("<span class=\"c_Green\"><i class=\"icon icon_status_success\"></i>正常</span>");
                }
            } else {
                $(".helper-setting-steamConnection").html("<span class=\"c_DRed\"><i class=\"icon icon_status_failed\"></i>无法连接</span>");
            }
        }

        function syncCurrency() {
            steamCurrency = g_rgCurrencyData[helper_config.steamCurrency];
            $("#helper-setting-currency").attr("value", steamCurrency.strCode);
            $("#helper-setting-currency>h3").text($("#helper-setting-currency li[value=" + steamCurrency.strCode + "]").addClass("on").text());
        }

        function parseColor() {
            market_color_high = helper_config.marketColorHigh.match(/[0-9a-f]{2}/ig);
            market_color_low = helper_config.marketColorLow.match(/[0-9a-f]{2}/ig);
            for (let i = 2; i >= 0; i--) {
                market_color_high[i] = parseInt(market_color_high[i], 16);
                market_color_low[i] = parseInt(market_color_low[i], 16);
            }
        }

        function sortGoods(sortRule, isAsc) {
            $("#j_list_card>ul>li").sort(function (a, b) {
                let av = $(a).attr(sortRule) - 0;
                let bv = $(b).attr(sortRule) - 0;
                let result = 0;
                if (isAsc) {
                    result = av - bv;
                } else {
                    result = bv - av;
                }
                return result === NaN ? 0 : result;
            }).appendTo("#j_list_card>ul");
        }

        function checkSteamConnection() {
            let interval = 0;
            $(".helper-setting-steamConnection").html("<span class=\"c_Blue\"><i class=\"icon icon_status_progressing\"></i>检测中</span>");
            $("#helper-setting-checkBtn").css("visibility", "hidden");
            let startTime = new Date().getTime();
            let endTime = 0;
            steamConnection = undefined;
            GM_xmlhttpRequest({
                url: "https://steamcommunity.com/market/",
                timeout: ajaxTimeout,
                method: "get",
                onloadstart: function (event) {
                    countdown(19);
                },
                onload: function (res) {
                    if (res && res.status == 200) {
                        endTime = new Date().getTime();
                        changeSteamStatus(true);
                    } else {
                        console.log("检测steam连接性出错：状态错误", res);
                        changeSteamStatus(false);
                    }
                },
                onerror: function (err) {
                    console.log("检测steam连接性出错：连接错误", err);
                    changeSteamStatus(false);
                },
                ontimeout: function () {
                    console.log("检测steam连接性出错：尝试超时");
                    changeSteamStatus(false);
                }
            });

            function changeSteamStatus(status) {
                clearInterval(interval);
                $(".steamConnectionCountdown").hide();
                steamConnection = status;
                if (status) {
                    $(".helper-setting-steamConnection").html("<span class=\"c_Green\"><i class=\"icon icon_status_success\"></i>正常</span><span class=\"c_DGray f_12px\">" + (endTime - startTime) + "ms</span>");
                } else {
                    $(".helper-setting-steamConnection").html("<span class=\"c_DRed\"><i class=\"icon icon_status_failed\"></i>无法连接</span>");
                }
                $("#helper-setting-checkBtn").css("visibility", "visible");
            }

            function countdown(count) {
                $(".steamConnectionCountdown").text("20s").show();
                interval = setInterval(() => {
                    $(".steamConnectionCountdown").text(count-- + "s");
                }, 1000);
            }
        }

        function failedSteamConnection() {
            if (++steamFailedTimes > (itemNum >> 2)) {
                steamConnection = false;
            }
        }

        function updateProgressBar(ID) {
            let bar = $("#helper-progress-bar-" + ID);
            bar.width(++itemCount / itemNum * 100 + "%")
            if (itemCount >= itemNum) {
                itemCount = 0;
                $("#helper-loading-" + ID).remove();
                bar.fadeOut(500);
            }
        }

        function paintingGradient(scale, target, position, template = '<strong class="f_16px f_Strong price_scale l_Right"></strong>') {
            let red = gradient(market_color_high[0], market_color_low[0], scale);
            let green = gradient(market_color_high[1], market_color_low[1], scale);
            let blue = gradient(market_color_high[2], market_color_low[2], scale);
            switch (position) {
                case 1:
                    $(target).before($(template).css("color", "rgb(" + red + "," + green + "," + blue + ")").text(scale));
                    break;
                case 2:
                    $(target).prepend($(template).css("color", "rgb(" + red + "," + green + "," + blue + ")").text(scale));
                    break;
                case 3:
                    $(target).append($(template).css("color", "rgb(" + red + "," + green + "," + blue + ")").text(scale));
                    break;
                case 4:
                    $(target).after($(template).css("color", "rgb(" + red + "," + green + "," + blue + ")").text(scale));
                    break;
                default:
                    $(target).append($(template).css("color", "rgb(" + red + "," + green + "," + blue + ")").text(scale));
            }
        }

        // 用来检测是否安装了其他buff插件，安装了就对布局做出相应调整防止排版混乱
        function daemonThread() {
            let count = 30
            let daemonThreadInterval = setInterval(() => {
                if (count--) {
                    if ($(".afkout").length || $("#infolist").length) {
                        $("#steam_order").remove();
                        $(".detail-summ>a").show();
                        $(".steam-link").hide();
                        clearInterval(daemonThreadInterval);
                    }
                } else {
                    clearInterval(daemonThreadInterval);
                }
            }, 100);
        }

        // json only
        function clone(obj) {
            return JSON.parse(JSON.stringify(obj));
        }

        // 小数： "167639.87", "167639", ".87", "87"
        // 整数： "186267",    "186267"
        function convertPrice(str) {
            str = str.replace(steamCurrency.strThousandsSeparator, "");
            if (steamCurrency.strDecimalSymbol !== ".") {
                str = str.replace(steamCurrency.strDecimalSymbol, ".");
            }
            return str.match(/(\d+)(\.(\d{1,2}))?/);
        }

        function addCurrencySymbol(origin, currencyCode) {
            let currencyData = g_rgCurrencyData[currencyCode];
            if (currencyData.bSymbolIsPrefix) {
                return currencyData.strSymbol + currencyData.strSymbolAndNumberSeparator + origin;
            } else {
                return origin + currencyData.strSymbolAndNumberSeparator + currencyData.strSymbol;
            }
        }

        // Foreign exchange to Chinese Yuan
        function FtoC(valueInCents) {
            if (steamCurrency.eCurrencyCode != 23 && (!helper_config.currencyEffectCalculate)) {
                return valueInCents * exchangeRate.FtoC;
            }
            return valueInCents;
        }
        // Chinese Yuan to Foreign exchange
        function CtoF(valueInCents) {
            if (steamCurrency.eCurrencyCode != 23 && (!helper_config.currencyEffectCalculate)) {
                return valueInCents * exchangeRate.CtoF;
            }
            return valueInCents;
        }

        // 这个函数的原作用是：
        function getScale(sellerPrice, buyerPriceInCents) {
            let amount = calculateFeeAmount(buyerPriceInCents);
            return (sellerPrice / v_currencyformat(amount.amount - amount.fees)).toFixed(2);
        }

        // symbolType 0, 1, 2
        // eg. originPrice = 4907856    (ARS, value in cents)
        // 0: 49078.56                  convert to float  
        // 1: ARS$ 49078.56             float with symbol
        // 2: ARS$ 49.078,56            locale string
        function getWithoutFeePrice(originPriceInCents, symbolType = 0, currencyCode = steamCurrency.strCode) {
            let amount = calculateFeeAmount(originPriceInCents);
            switch (symbolType) {
                case 0:
                    return v_currencyformat(amount.amount - amount.fees);
                case 1:
                    return addCurrencySymbol(v_currencyformat(amount.amount - amount.fees), currencyCode);
                case 2:
                    return v_currencyformat(amount.amount - amount.fees, currencyCode);
            }
        }

        function showMessage(title, msg, type = "info", time = 5000, position = 'top-right') {
            return $.toast({
                text: msg,
                heading: title,
                icon: type,
                showHideTransition: 'fade', // fade, slide or plain
                allowToastClose: true,
                hideAfter: time, // false to make it sticky or number representing the miliseconds as time after which toast needs to be hidden
                stack: 5, // false if there should be only one toast at a time or a number representing the maximum number of toasts to be shown at a time
                position: position, // bottom-left or bottom-right or bottom-center or top-left or top-right or top-center or mid-center or an object representing the left, right, top, bottom values
                textAlign: 'left',  // Text alignment i.e. left, right or center
                // loader: false,  // Whether to show loader or not. True by default    没看懂loader什么意思¯\(°_o)/¯
                // loaderBg: '#9EC600',  // Background color of the toast loader
                // beforeShow: function () {}, // will be triggered before the toast is shown
                // afterShown: function () {}, // will be triggered after the toat has been shown
                // beforeHide: function () {}, // will be triggered before the toast gets hidden
                // afterHidden: function () {}  // will be triggered after the toast has been hidden
            });
        }

        function gradient(max, min, f) {
            if (f == "∞") { return max; }
            if (f >= helper_config.maxRange || f <= helper_config.minRange) {
                f = f >= helper_config.maxRange ? 1 : 0;
            } else {
                f = (f - helper_config.minRange) / (helper_config.maxRange - helper_config.minRange);
            }
            return max >= min ? f * (max - min) + min : (1 - f) * (min - max) + max;
        }

        function getGoodsId() {
            let result = location.pathname.match(/\/goods\/(\d+)/);
            if (result) return result[1]; return null;
        }

        function escape(englishName) {
            return encodeURIComponent(englishName).replaceAll("(", "%28").replaceAll(")", "%29");
        }

        // --------------------- copy from steam -----------------------
        // 售价算税
        function calculateFeeAmount(amount) {
            if (!g_rgWalletInfo['wallet_fee'])
                return 0;

            var publisherFee = (typeof g_rgWalletInfo['wallet_publisher_fee_percent_default'] == 'undefined') ? 0 : g_rgWalletInfo['wallet_publisher_fee_percent_default'];

            // Since CalculateFeeAmount has a Math.floor, we could be off a cent or two. Let's check:
            var iterations = 0; // shouldn't be needed, but included to be sure nothing unforseen causes us to get stuck
            var nEstimatedAmountOfWalletFundsReceivedByOtherParty = parseInt((amount - parseInt(g_rgWalletInfo['wallet_fee_base'])) / (parseFloat(g_rgWalletInfo['wallet_fee_percent']) + parseFloat(publisherFee) + 1));

            var bEverUndershot = false;
            var fees = CalculateAmountToSendForDesiredReceivedAmount(nEstimatedAmountOfWalletFundsReceivedByOtherParty, publisherFee);
            while (fees.amount != amount && iterations < 10) {
                if (fees.amount > amount) {
                    if (bEverUndershot) {
                        fees = CalculateAmountToSendForDesiredReceivedAmount(nEstimatedAmountOfWalletFundsReceivedByOtherParty - 1, publisherFee);
                        fees.steam_fee += (amount - fees.amount);
                        fees.fees += (amount - fees.amount);
                        fees.amount = amount;
                        break;
                    }
                    else {
                        nEstimatedAmountOfWalletFundsReceivedByOtherParty--;
                    }
                }
                else {
                    bEverUndershot = true;
                    nEstimatedAmountOfWalletFundsReceivedByOtherParty++;
                }

                fees = CalculateAmountToSendForDesiredReceivedAmount(nEstimatedAmountOfWalletFundsReceivedByOtherParty, publisherFee);
                iterations++;
            }

            // fees.amount should equal the passed in amount
            return fees;

            function CalculateAmountToSendForDesiredReceivedAmount(receivedAmount, publisherFee) {
                if (!g_rgWalletInfo['wallet_fee']) {
                    return receivedAmount;
                }

                publisherFee = (typeof publisherFee == 'undefined') ? 0 : publisherFee;

                var nSteamFee = parseInt(Math.floor(Math.max(receivedAmount * parseFloat(g_rgWalletInfo['wallet_fee_percent']), g_rgWalletInfo['wallet_fee_minimum']) + parseInt(g_rgWalletInfo['wallet_fee_base'])));
                var nPublisherFee = parseInt(Math.floor(publisherFee > 0 ? Math.max(receivedAmount * publisherFee, 1) : 0));
                var nAmountToSend = receivedAmount + nSteamFee + nPublisherFee;

                return {
                    steam_fee: nSteamFee,
                    publisher_fee: nPublisherFee,
                    fees: nSteamFee + nPublisherFee,
                    amount: parseInt(nAmountToSend)
                };
            }
        }
        // 小数点左移两位，并且加货币符号（可选）
        function v_currencyformat(valueInCents, currencyCode) {
            var currencyFormat = `${parseInt(valueInCents = Math.abs(+valueInCents / 100 || 0).toFixed(2), 10)}`;

            if (g_rgCurrencyData[currencyCode]) {
                var currencyData = g_rgCurrencyData[currencyCode];

                const j = (currencyFormat.length > 3 ? currencyFormat.length % 3 : 0);
                const thousand_formatted = `${j ? currencyFormat.substr(0, j) + currencyData.strThousandsSeparator : ''}${currencyFormat.substr(j).replace(/(\d{3})(?=\d)/g, `$1${currencyData.strThousandsSeparator}`)}`;
                const decimal_formatted = `${currencyData.strDecimalSymbol}${Math.abs(valueInCents - currencyFormat).toFixed(2).slice(2)}`;
                const formatted = `${thousand_formatted}${currencyData.bWholeUnitsOnly ? decimal_formatted.replace(`${currencyData.strDecimalSymbol}00`, '') : decimal_formatted}`;

                var currencyReturn = currencyData.bSymbolIsPrefix
                    ? `${currencyData.strSymbol}${currencyData.strSymbolAndNumberSeparator}${formatted}`
                    : `${formatted}${currencyData.strSymbolAndNumberSeparator}${currencyData.strSymbol}`;

                if (currencyCode == 'USD') {
                    return currencyReturn + ' USD';
                }
                else if (currencyCode == 'EUR') {
                    return currencyReturn.replace(',00', ',--');
                }
                else {
                    return currencyReturn;
                }
            }
            else {
                return valueInCents;
            }
        }
        // ---------------------- end ------------------------

        function errorTranslator(err) {
            const msg = {
                "0": "访问steam失败，请检查网络连接性",
                "200": "无法处理结果，结果集无法使用",
                "400": "请求参数错误，服务器无法理解参数",
                "404": "页面不存在，无法找到请求的资源",
                "408": "访问steam超时，请检查网络连接性",
                "429": "请求次数过多，饮个茶再来吧",
                "500": "服务器内部错误，请稍后重试"
            };
            const shortMsg = {
                "0": "无网络",
                "200": "请重试",
                "400": "参数错误",
                "404": "无内容",
                "408": "超时",
                "429": "频繁",
                "500": "请重试"
            };
            switch (err.status) {
                case 0:
                    failedSteamConnection();
                    break;
                case 429:
                    steamConnection = true;
                    break;
            }
            err.statusText = msg[err.status];
            err.statusTextShort = shortMsg[err.status];
            return err;
        }

        function updateRate(force, toast) {
            if ((!force) && exchangeRate && exchangeRate.time_next_update_unix > Date.now()) {
                return;
            }
            if ((!steamConnection) && steamConnection != undefined) {
                toast && toast.reset();
                showMessage("无网络时无法获取汇率", "没有设置被改变", 'warning');
                return;
            }

            // let url = `https://steamcommunity.com/market/listings/730/Souvenir%20Sawed-Off%20|%20Snake%20Camo%20(Well-Worn)/render/?query=&start=40&count=100&currency=${g_rgCurrencyData[helper_config.steamCurrency].eCurrencyCode}`
            // let url = `https://steamcommunity.com/market/listings/730/AK-47%20%7C%20Cartel%20%28Field-Tested%29/render/?query=&start=40&count=100&currency=${g_rgCurrencyData[helper_config.steamCurrency].eCurrencyCode}`;
            let url = `https://steamcommunity.com/market/listings/730/AWP%20%7C%20Crakow%21%20%28Minimal%20Wear%29/render/?currency=${g_rgCurrencyData[helper_config.steamCurrency].eCurrencyCode}`;
            // https://steamcommunity.com/market/listings/730/AWP%20%7C%20Crakow%21%20%28Minimal%20Wear%29/render/?currency=1
            info("汇率url：", url);
            GM_xmlhttpRequest({
                // 10000元锚点
                url: url,

                // 热门锚点
                // https://steamcommunity.com/market/listings/730/AK-47%20%7C%20Cartel%20%28Field-Tested%29/render/?query=&start=40&count=100&currency=1
                // https://steamcommunity.com/market/listings/730/Souvenir%20Sawed-Off%20|%20Snake%20Camo%20(Well-Worn)/render/?query=&start=40&count=100&currency=1
                // url: `https://steamcommunity.com/market/listings/730/AWP%20|%20Redline%20(Minimal%20Wear)/render/?start=0&count=30&currency=${g_rgCurrencyData[helper_config.steamCurrency].eCurrencyCode}`,
                method: "get",
                timeout: ajaxTimeout,
                onload: function (response) {
                    toast && toast.reset();
                    let data = response.responseText;
                    info("汇率返回的结果: request_URL: "+url+'; data: '+data);
                    data = response.status == 200 ? JSON.parse(data) : {};
                    info(`laoyudbg line 2108: 更新汇率时 data的值`);
                    info(data);
                    console.log(data.listinginfo);
                    // if (data.success && data.listinginfo["3296062994072312107"]) {
                    // if (data.success && data.listinginfo["5392588182779643817"]) {
                    //     if (data.listinginfo["5392588182779643817"].converted_currencyid % 2000 != g_rgCurrencyData[helper_config.steamCurrency].eCurrencyCode) {
                    //         return; // 对结果返回前的多次操作进行屏蔽，只取最后一次的结果
                    //     }
                    //     let timeUnix = Date.now();

                    //     // 更新当前汇率
                    //     // exchangeRate = {
                    //     //     FtoC: (data.listinginfo["3296062994072312107"].price / data.listinginfo["3296062994072312107"].converted_price).toFixed(6),
                    //     //     CtoF: (data.listinginfo["3296062994072312107"].converted_price / data.listinginfo["3296062994072312107"].price).toFixed(6),
                    //     //     currencyCode: g_rgCurrencyData[helper_config.steamCurrency].strCode,
                    //     //     time_next_update_unix: timeUnix + 10800000,
                    //     //     time_update_unix: timeUnix
                    //     // }

                    //     // 5392588182779643817 这个数字怎么来的我也不清楚，请求这个接口之后，第一条数据的id我就直接拿过来用了
                    //     exchangeRate = {
                    //         FtoC: (data.listinginfo["5392588182779643817"].price / data.listinginfo["5392588182779643817"].converted_price).toFixed(6),
                    //         CtoF: (data.listinginfo["5392588182779643817"].converted_price / data.listinginfo["5392588182779643817"].price).toFixed(6),
                    //         currencyCode: g_rgCurrencyData[helper_config.steamCurrency].strCode,
                    //         time_next_update_unix: timeUnix + 10800000,
                    //         time_update_unix: timeUnix
                    //     }
                    //     console.log(`【laoyudbg】 line 1458: 更新当前汇率：${exchangeRate}`);
                    //     GM_setValue("exchangeRate", exchangeRate);
                    //     GM_setValue("helper_config", helper_config);
                    //     showMessage("获取汇率成功", `已经同步${helper_config.steamCurrency}的最新汇率`, "success");
                    //     return;
                    // }
                    if (data.success && data.listinginfo) {
                        let guji_listingId = '';
                        for (let i in data.listinginfo) {
                            console.log(data.listinginfo[i].price / data.listinginfo[i].converted_price);
                            if (parseInt(data.listinginfo[i].price / data.listinginfo[i].converted_price) == 7) {
                                guji_listingId = i;
                                break;
                            }
                        }
                        if (data.listinginfo[guji_listingId].converted_currencyid % 2000 != g_rgCurrencyData[helper_config.steamCurrency].eCurrencyCode) {
                            return; // 对结果返回前的多次操作进行屏蔽，只取最后一次的结果
                        }
                        let timeUnix = Date.now();

                        // 更新当前汇率
                        // exchangeRate = {
                        //     FtoC: (data.listinginfo["3296062994072312107"].price / data.listinginfo["3296062994072312107"].converted_price).toFixed(6),
                        //     CtoF: (data.listinginfo["3296062994072312107"].converted_price / data.listinginfo["3296062994072312107"].price).toFixed(6),
                        //     currencyCode: g_rgCurrencyData[helper_config.steamCurrency].strCode,
                        //     time_next_update_unix: timeUnix + 10800000,
                        //     time_update_unix: timeUnix
                        // }

                        // 5392588182779643817 这个数字怎么来的我也不清楚，请求这个接口之后，第一条数据的id我就直接拿过来用了
                        exchangeRate = {
                            FtoC: (data.listinginfo[guji_listingId].price / data.listinginfo[guji_listingId].converted_price).toFixed(6),
                            CtoF: (data.listinginfo[guji_listingId].converted_price / data.listinginfo[guji_listingId].price).toFixed(6),
                            currencyCode: g_rgCurrencyData[helper_config.steamCurrency].strCode,
                            time_next_update_unix: timeUnix + 10800000,
                            time_update_unix: timeUnix
                        }
                        console.log(`【laoyudbg】: 更新当前汇率: `, exchangeRate);
                        GM_setValue("exchangeRate", exchangeRate);
                        GM_setValue("helper_config", helper_config);
                        showMessage("获取汇率成功", `已经同步${helper_config.steamCurrency}的最新汇率`, "success");
                        return;
                    }

                    // in case of emergency
                    // if (data.success) {
                    //     for (let key in data.listinginfo) {
                    //         if (data.listinginfo[key].currencyid == 2023) {
                    //             if (data.listinginfo[key].converted_currencyid % 2000 != g_rgCurrencyData[helper_config.steamCurrency].eCurrencyCode) {return;}
                    //             let timeUnix = Date.now();
                    //             exchangeRate = {
                    //                 FtoC: (data.listinginfo[key].price / data.listinginfo[key].converted_price).toFixed(6),
                    //                 CtoF: (data.listinginfo[key].converted_price / data.listinginfo[key].price).toFixed(6),
                    //                 currencyCode: g_rgCurrencyData[helper_config.steamCurrency].strCode,
                    //                 time_next_update_unix: timeUnix + 10800000,
                    //                 time_update_unix: timeUnix
                    //             }
                    //             GM_setValue("exchangeRate", exchangeRate);
                    //             GM_setValue("helper_config", helper_config);
                    //             showMessage("获取汇率成功", `已经同步${helper_config.steamCurrency}的最新汇率`, "success");
                    //             return;
                    //         }
                    //     }
                    // }
                    // console.log("获取汇率时错误：", response);
                    // console.log("获取汇率时错误的具体响应是：", response.response, response.response.listinginfo);
                    showMessage("获取汇率时错误", errorTranslator(response).statusText, 'error');
                },
                onerror: function (err) {
                    console.log("获取汇率失败：", err);
                    showMessage("获取汇率失败", errorTranslator(err).statusText, 'error');
                },
                ontimeout: function () {
                    failedSteamConnection();
                    let err = { "status": 408, "statusText": "连接steam超时，请检查steam市场连接性" };
                    console.log("获取汇率超时：", err);
                    showMessage("获取汇率超时", err.statusText, 'error');
                }
            });
        }

        function getItemId(buff_item_id, steamLink) {
            return new Promise(function (resolve, reject) {
                let steam_item_id = GM_getValue(buff_item_id);
                if (steam_item_id) {
                    resolve(steam_item_id);
                    return;
                } else if (steam_item_id === null) {
                    reject({ status: 404, statusText: "物品不在货架上" });
                }
                GM_xmlhttpRequest({
                    url: steamLink,
                    timeout: ajaxTimeout,
                    method: "get",
                    onload: function (res) {
                        if (res.status == 200) {
                            let html = res.responseText;  // 页面很大
                            try {
                                steam_item_id = /Market_LoadOrderSpread\(\s?(\d+)\s?\)/.exec(html)[1];
                            } catch (error) {
                                steamConnection = true;
                                GM_setValue(buff_item_id, null);
                                res.status = 404;
                                res.statusText = "物品不在货架上";
                                console.log("获取itemID状态异常：", res);
                                reject(res);
                                return;
                            }
                            GM_setValue(buff_item_id, steam_item_id);
                            resolve(steam_item_id);
                        } else {
                            console.log("获取itemID状态异常：", res);
                            reject(errorTranslator(res));
                        }
                    },
                    onerror: function (err) {
                        console.log("获取itemID错误：", err);
                        reject(errorTranslator(err));
                    },
                    ontimeout: function () {
                        failedSteamConnection();
                        let err = { "status": 408, "statusText": "连接steam超时，请检查steam市场连接性" };
                        console.log("获取itemID超时：", err);
                        reject(err);
                    }
                });
            });
        }

        function getSteamOrderList(buff_item_id, steamLink) {
            return new Promise(function (resolve, reject) {
                if ((!steamConnection) && steamConnection != undefined) {
                    let err = { "status": 408, "statusText": "无法访问steam" };
                    resolve(err);
                    return;
                }
                getItemId(buff_item_id, steamLink).then(function onFulfilled(steam_item_id) {
                    GM_xmlhttpRequest({
                        url: `https://steamcommunity.com/market/itemordershistogram?country=CN&language=schinese&currency=${steamCurrency.eCurrencyCode}&item_nameid=${steam_item_id}&two_factor=0`,
                        timeout: ajaxTimeout,
                        headers: {
                            "referer": steamLink,
                            "X-Requested-With": "XMLHttpRequest",
                            "Host": "steamcommunity.com",
                            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35"
                        },
                        method: "get",
                        onload: function (res) {
                            if (res.status == 200) {
                                steamConnection = true;
                                info("尝试输出一下，看看是不是steam求购列表");
                                info(JSON.parse(res.responseText));     // 尝试输出一下，看看是不是steam求购列表
                                resolve(JSON.parse(res.responseText));
                                return;
                            }
                            console.log("访问steamorder状态异常：", res);
                            resolve(errorTranslator(res));
                        },
                        onerror: function (err) {
                            console.log("访问steamorder列表出错：", err);
                            resolve(errorTranslator(err));
                        },
                        ontimeout: function () {
                            failedSteamConnection();
                            let err = { "status": 408, "statusText": "连接steam超时，请检查steam市场连接性" };
                            console.log("访问steamorder列表超时：", err);
                            resolve(err);
                        }
                    });
                }).catch(function onRejected(err) {
                    resolve(err);
                });
            });
        }

        function getSteamSoldNumber(app_id, hash_name) {
            return new Promise(function (resolve) {
                if ((!steamConnection) && steamConnection != undefined) {
                    let err = { "status": 408, "statusText": "无法访问steam" };
                    resolve(err);
                    return;
                }
                GM_xmlhttpRequest({
                    url: `https://steamcommunity.com/market/priceoverview/?appid=${app_id}&currency=${steamCurrency.eCurrencyCode}&market_hash_name=${hash_name}`,
                    timeout: ajaxTimeout,
                    headers: {
                        "referer": `https://steamcommunity.com/market/listings/${app_id}/${hash_name}`,
                        "X-Requested-With": "XMLHttpRequest",
                        "Host": "steamcommunity.com",
                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.35"
                    },
                    method: "get",
                    onload: function (res) {
                        if (res.status == 200) {
                            steamConnection = true;
                            let json = JSON.parse(res.responseText);
                            if (json.success) {
                                resolve(json);
                                return;
                            }
                        }
                        console.log("访问steam销售数量状态异常：", res);
                        resolve(errorTranslator(res));
                    },
                    onerror: function (err) {
                        console.log("访问steam销售数量出错：", err);
                        resolve(errorTranslator(err));
                    },
                    ontimeout: function () {
                        failedSteamConnection();
                        let err = { "status": 408, "statusText": "连接steam超时，请检查steam市场连接性" };
                        console.log("访问steam销售数量超时：", err);
                        resolve(err);
                    }
                });
            });
        }

        // 卡价这个概念不是特别情清晰
        // function get_cardPrice() {
        //     let 汇率 = GM_getValue("exchangeRate").FtoC
        //     let 一百美金人民币卡价 = helper_config.cardPrice             // 1
        //     let 一百美金人民币正价 = (100*汇率);
        //     let 一美金实际成本 = (一百美金人民币卡价/一百美金人民币正价);   // 相当于一美金充值st进去后真正有多少钱
        //     return 一美金实际成本;
        // }

        function 正推利润公式(steam求购价, buff卖价, 卡价) {
            // let 卡价 = 5.75;  // get_cardPrice();
            let 交易税后价 = buff卖价 * 0.975;                 // Buff去税毛利 = Buff最低出售价 * 0.975
            let 提现手续费 = 交易税后价 * 0.01;
            let 成本 = steam求购价 * 卡价;                     // 成本 = steam求购价 * 一美金实际成本
            let 利润金额 = 交易税后价 - 提现手续费 - 成本;      // 净利润 = Buff纯毛利 - 成本
            let 利润率 = 利润金额 / 成本;                      // 利润率 = 净利润 / 成本
            利润率 = (利润率 * 100).toFixed(2);
            return 利润率;
        }

        // 反推利润公式的利润率参数应该要传递百分号前面的值
        function 反推利润公式(利润率, buff卖价, 卡价) {
            // let 卡价 = 5.75;  // get_cardPrice();
            利润率 = 利润率 / 100;     // 去除百分号（待优化）
            let 交易税后价 = buff卖价 * 0.975;
            let 提现手续费 = 交易税后价 * 0.01;
            let steam求购价 = (交易税后价 - 提现手续费) / (卡价 + 利润率 * 卡价)
            steam求购价 = steam求购价.toFixed(2);
            // info();
            //         console.log(`利润率: ${利润率}\n交易税后价: buff卖价 * 0.975 = ${交易税后价}
            // 提现手续费: 交易税后价 * 0.01 = ${提现手续费}\nst求购价: ${steam求购价}
            // 交易税后价 - 提现手续费: ${交易税后价 - 提现手续费}
            // 卡价 + 利润率 * 卡价 = ${卡价 + 利润率 * 卡价}`);
            return steam求购价;
        }

        function 利润率反推卖价(利润率, st求购价, 卡价) {
            利润率 = (利润率 / 100) + 1;     // 去除百分号（待优化）
            let buff卖价 = (st求购价 * 利润率 * 卡价) / 0.96525;
            buff卖价 = buff卖价.toFixed(2);
            return buff卖价;
        }

        function fast_calc_box_func() {
            // 添加计算利润小窗口联动计算功能
            // 获取对应的dom
            let buymoney = document.getElementById("buymoney");                              // steam求购价
            let sellmoney = document.getElementById("sellmoney");                            // buff卖价
            let profit_margin = document.getElementById("profit_margin");                    // 利润率
            let cardPrice = document.getElementById("helper-setting-pageCardPrice");         // 卡价（由小窗口移动到设置页面）

            buymoney.oninput = function() {
                let buy = parseFloat(buymoney.value);
                let sell = parseFloat(sellmoney.value);
                let cardPrice_v = parseFloat(cardPrice.value);
                info("监听到 *steam求购价* 被修改  ->  即将修改 *利润率*");
                info(`steam求购价: ${buy}\nbuff卖价: ${sell}\n卡价: ${cardPrice_v}`);
                let rate = 正推利润公式(buy, sell, cardPrice_v);
                info(`计算得出利润率为: ${rate}%`);
                profit_margin.value = rate;
            };

            sellmoney.oninput = function() {
                let buy = parseFloat(buymoney.value);
                let sell = parseFloat(sellmoney.value);
                let cardPrice_v = parseFloat(cardPrice.value);
                info("监听到 *steam求购价* 被修改  ->  即将修改 *利润率*");
                info(`steam求购价: ${buy}\nbuff卖价: ${sell}\n卡价: ${cardPrice_v}`);
                let rate = 正推利润公式(buy, sell, cardPrice_v);
                info(`计算得出利润率为: ${rate}%`);
                profit_margin.value = rate;
            };

            profit_margin.oninput = function() {
                let sell = parseFloat(sellmoney.value);
                let rate = parseFloat(profit_margin.value);
                let cardPrice_v = parseFloat(cardPrice.value);
                info("监听到 *利润率* 被修改  ->  即将修改 *steam求购价*");
                info(`buff卖价: ${sell}\n利润率: ${rate}\n卡价: ${cardPrice_v}`);
                let buy = 反推利润公式(rate, sell, cardPrice_v);
                info(`计算得出steam求购价为: ${buy}%`);
                buymoney.value = buy;
            };

            cardPrice.oninput = function() {
                let buy = parseFloat(buymoney.value);
                let sell = parseFloat(sellmoney.value);
                let cardPrice_v = parseFloat(cardPrice.value);
                // helper_config.helperCardPrice = cardPrice_v;
                info("监听到 *卡价* 被修改  ->  即将修改 *利润率*");
                info(`steam求购价: ${buy}\nbuff卖价: ${sell}\n卡价: ${cardPrice_v}`);
                let rate = 正推利润公式(buy, sell, cardPrice_v);
                info(`计算得出利润率为: ${rate}%`);
                profit_margin.value = rate;
            };
        }

        function info(...params) {
            if (debugflag) console.log(...params);
        }

        function show_st_buymoney() {
            // 这个函数应该修改为两个函数，一个是在页面添加st求购价，一个是修改页面中的求购价
            // 使用全局变量 added_st_box_flag 来控制
            // 当 added_st_box_flag = false 时 为添加st求购价
            // 当 added_st_box_flag = true  时 为修改st求购价
            // 
            if (added_st_box_flag) {
                // 修改st求购价
                // 获取所有商品
                let all_goods = $("#j_list_card>ul>li");
                for (let i = 0; i < all_goods.length; i++) {
                    let target = all_goods[i];                                // 显示价格的那一行 p元素
                    let target_ = target.querySelector('.st-buymoney-box');   // 显示图片的那一行 a元素
                    // 获取当前价格
                    target = target.children[2].children[0];
                    if (target.children.length == 0 || target.children[0].nodeName == 'SMALL') {
                        target = target.innerText;
                    } else {
                        // 检测价格是否有小数点
                        if (target.children[1].nodeName == 'SMALL') {
                            target = target.children[0].innerText + target.children[1].innerText;
                        } else {
                            target = target.children[0].innerText;
                        }
                    }
                    target = target.slice(2);
                    // 求出st求购价
                    let st求购价 = 反推利润公式(
                        parseFloat(helper_config.reCalcProfitMargin), parseFloat(target),
                        parseFloat(helper_config.helperCardPrice)
                    );
                    // 更新页面中的信息
                    let tmp_string = "当前反推求购价$" + st求购价;
                    target_.innerText = tmp_string;
                    // info(`成功设置第${i+1}个`);
                }
            } else {
                // 添加st求购价
                // 检测商品是否加载完成
                if ($("#j_list_card>ul>li").length == 0) {
                    setTimeout(show_st_buymoney, 300);
                    return;
                }
                // 遍历所有的商品buff卖价
                // let all_goods = document.querySelector("#j_list_card > ul").children;
                let all_goods = $("#j_list_card>ul>li");
                for (let i = 0; i < all_goods.length; i++) {
                    // 获取商品的buff卖价
                    let target = all_goods[i];
                    target = target.children[2].children[0].innerText;
                    target = target.slice(2);
                    // info("获取商品价格"+target);
                    // 计算对应商品的st求购价
                    let st求购价 = 反推利润公式(
                        parseFloat(helper_config.reCalcProfitMargin), parseFloat(target),
                        parseFloat(helper_config.helperCardPrice)
                    );
                    // 显示在页面中
                    // let tmp_string = "当前反推求购价" + g_rgCurrencyData[helper_config.steamCurrency]["strSymbol"] + st求购价;
                    let tmp_string = "当前反推求购价$" + st求购价;
                    // info(tmp_string);
                    let tmp_span = document.createElement("span");
                    tmp_span.className = "st-buymoney-box";
                    tmp_span.innerText = tmp_string;
                    document.querySelectorAll("#j_list_card>ul>li")[i].children[0].appendChild(tmp_span);
                }
            }
            added_st_box_flag = true;
        }

        // 获取目前同浏览器下登录态的steam账户信息（主要是用户名和steamID）
        function getSteamAccountInfo() {
            GM_xmlhttpRequest({
                url: "https://store.steampowered.com/account/",
                timeout: 2000,
                method: 'get',
                onload: function (res) {
                    if (res && res.status == 200) {
                        info("获取目前同浏览器下登录态的steam账户信息（主要是用户名和steamID）");
                        // 获取响应的html文档
                        let resText = res.responseText;
                        // 使用DOM解析器
                        let parser = new DOMParser();
                        // 解析html文档
                        let VMDOM = parser.parseFromString(resText, "text/html");
                        // 读取用户名和ID对应的DOM值并输出
                        let steamUserName = VMDOM.querySelector(".youraccount_pageheader").innerText;
                        let steamID = VMDOM.querySelector(".youraccount_steamid").innerText;
                        info("【new】steam用户名：" + steamUserName);
                        info("【new】steamID：" + steamID);
                        sessionStorage.setItem("steamUserName", steamUserName);
                        sessionStorage.setItem("steamID", steamID);
                    } else {
                        console.log("检测到steam连接性出错：状态错误", res);
                    }
                },
                onerror: function (err) {
                    console.log("检测到steam连接性出错：连接错误", err);
                },
                ontimeout: function () {
                    console.log("检测到steam连接性出错：尝试超时");
                }
            });
        }

        // 添加设置账单地址功能
        function add_set_account_address_btn() {
            let btn = document.querySelector("body > div.calc-profit-box > div:nth-child(1) > div:nth-child(2) > span");
            let box_shadow = document.querySelector('.setting_steam_account_address_shadow');
            let box = document.querySelector('.setting_steam_account_address');

            // 添加点击事件
            btn.addEventListener('click', function (e) {
                if (box_shadow.style.display == 'block') {
                    box_shadow.style.display = 'none';
                } else {
                    box_shadow.style.display = 'block';
                    // 清除steamID和steamUserName
                    box.querySelector('.steamID').innerText = '获取中...';
                    box.querySelector('.steamUserName').innerText = '获取中...';
                    // 将更新后的信息展示出来
                    let zhangdandizhi = localStorage.getItem("zhangdandizhi") ? JSON.parse(localStorage.getItem("zhangdandizhi")): {
                        name: "",
                        first_name: "",
                        address1: "",
                        address2: "",
                        city: "",
                        sheng: "AK",
                        youzhengcode: ""
                    };
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-name > span:nth-child(2) > input[type=text]").value = zhangdandizhi.name;
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-name > span:nth-child(4) > input[type=text]").value = zhangdandizhi.first_name;
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-address > span:nth-child(2) > input[type=text]").value = zhangdandizhi.address1;
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-address > span:nth-child(4) > input[type=text]").value = zhangdandizhi.address2;
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-city > span:nth-child(2) > input[type=text]").value = zhangdandizhi.city;
                    document.querySelector("#zhousheng").value = zhangdandizhi.sheng;
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-country > span:nth-child(2) > input[type=text]").value = zhangdandizhi.youzhengcode;
                    // 展示此时为登录态的steam账号ID和steam账号名称
                    let steamUserName = sessionStorage.getItem("steamUserName");
                    let steamID = sessionStorage.getItem("steamID");
                    box.querySelector('.steamID').innerText = steamID;
                    box.querySelector('.steamUserName').innerText = steamUserName;
                    
                }
            });

            // 隐藏界面的事件
            box_shadow.addEventListener('click', function (e) {
                box_shadow.style.display = 'none';
            });

            // 操作界面时阻止界面被隐藏
            box.addEventListener('click', function (e) {
                e.stopPropagation();
            });

            // 监听所有输入框的改变，并实时保存到 localStorage 里面
            (function () {
                let allInputDOM = [
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-name > span:nth-child(2) > input[type=text]"),
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-name > span:nth-child(4) > input[type=text]"),
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-address > span:nth-child(2) > input[type=text]"),
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-address > span:nth-child(4) > input[type=text]"),
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-city > span:nth-child(2) > input[type=text]"),
                    document.querySelector("#zhousheng"),
                    document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-country > span:nth-child(2) > input[type=text]")
                ];
    
                let listen_change_event = function (e) {
                    let zhangdandizhi = {
                        name: document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-name > span:nth-child(2) > input[type=text]").value,
                        first_name: document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-name > span:nth-child(4) > input[type=text]").value,
                        address1: document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-address > span:nth-child(2) > input[type=text]").value,
                        address2: document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-address > span:nth-child(4) > input[type=text]").value,
                        city: document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-city > span:nth-child(2) > input[type=text]").value,
                        sheng: document.querySelector("#zhousheng").value,
                        youzhengcode: document.querySelector("body > div.setting_steam_account_address_shadow > div > div.steam-country > span:nth-child(2) > input[type=text]").value
                    }
                    zhangdandizhi = JSON.stringify(zhangdandizhi);
                    localStorage.setItem('zhangdandizhi', zhangdandizhi);
                    info(zhangdandizhi);
                }

                for (let i = 0; i < allInputDOM.length; i++) {
                    allInputDOM[i].addEventListener('change', listen_change_event);
                }

            })();

            info('【set btn】查看设置账单地址界面按钮');
        }

        // 查询所有订购单按钮功能
        function add_get_all_order_list_btn() {
            let btn = document.querySelector("body > div.calc-profit-box > div:nth-child(2) > div > span");
            let box_shadow = document.querySelector('.select_steam_commited_orders_shadow');
            let box = document.querySelector('.select_steam_commited_orders');

            // 添加点击事件
            btn.addEventListener('click', function (e) {
                if (box_shadow.style.display == 'block') {
                    box_shadow.style.display = 'none';
                } else {
                    box_shadow.style.display = 'block';
                    box.querySelector('.loadingSteamCommitedOrdersTbody').style.display = 'block';
                    let tbody = box.querySelector('.steamCommitedOrdersTbody');
                    tbody.style.display = 'none';
                    // 删除页面中原有的信息
                    // 清除steamID和steamUserName
                    box.querySelector('.steamID').innerText = '获取中...';
                    box.querySelector('.steamUserName').innerText = '获取中...';
                    // 清除原有订购单列表
                    tbody.innerHTML = '';
                    // 展示此时为登录态的steam账号ID和steam账号名称
                    let steamUserName = sessionStorage.getItem("steamUserName");
                    let steamID = sessionStorage.getItem("steamID");
                    box.querySelector('.steamID').innerText = steamID;
                    box.querySelector('.steamUserName').innerText = steamUserName;
                    // 展示所有订购单
                    get_all_order_list(box);
                }
            });

            // 隐藏界面的事件
            box_shadow.addEventListener('click', function (e) {
                box_shadow.style.display = 'none';
            });

            // 操作界面时阻止界面被隐藏
            box.addEventListener('click', function (e) {
                e.stopPropagation();
            });

            info('【set btn】查看已提交订购单数额按钮');
        }

        // 获取当前所有订购单
        function get_all_order_list(box) {
            GM_xmlhttpRequest({
                url: "https://steamcommunity.com/market/",
                timeout: 5000,
                method: 'get',
                onload: function (res) {
                    if (res && res.status == 200) {
                        // 获取响应的html文档
                        let resText = res.responseText;
                        // 使用DOM解析器
                        let parser = new DOMParser();
                        // 解析html文档
                        let VMDOM = parser.parseFromString(resText, "text/html");
                        info("【new】获取当前所有订购单");
                        // 读取所有订购单
                        let order_list = VMDOM.querySelectorAll('[id^="mybuyorder_"].market_recent_listing_row');
                        info(order_list);
                        // 获取tbody
                        let tbody = box.querySelector('.steamCommitedOrdersTbody');
                        // 获取历史订单 并逐一对比
                        GM_xmlhttpRequest({
                            url: "https://steamcommunity.com/market/myhistory/render/?query=&start=0&count=500",
                            timeout: 5000,
                            method: 'get',
                            onload: function (res) {
                                // 获取响应的html文档
                                let resText = res.responseText;
                                let resJson = JSON.parse(resText);
                                info('【获取历史订购单的结果】', resJson);
                                resText = resJson.results_html;
                                // 使用DOM解析器
                                let parser = new DOMParser();
                                let VMDOM = parser.parseFromString(resText, "text/html");
                                // 获取历史订单列表
                                let history_list = VMDOM.querySelectorAll('.market_listing_row');
                                // 获取所有订购单
                                let res_list = {};
                                for (let i = 0; i < history_list.length; i++) {
                                    let orderGoodName = history_list[i].querySelector('.market_listing_item_name').innerText;
                                    res_list[orderGoodName] = (res_list[orderGoodName] ? res_list[orderGoodName] : 0) + 1;
                                }
                                info('【测试代码：所有历史订购单】', res_list);
                                // 顶部表示一共多少个的变量
                                let total_count = 0;
                                // 顶部表示一共有多少钱
                                let total_price = 0;
                                // 输出所有订购单
                                for (let i = 0; i < order_list.length; i++) {
                                    // info(order_list[i]);
                                    let orderID = order_list[i].getAttribute('id').split('_')[1];
                                    let orderGoodsName = order_list[i].querySelector('.market_listing_item_name_link').innerText;
                                    let orderGoodsPrice = order_list[i].querySelector('.market_listing_price').innerText.split('@')[1];
                                    let orderGoodsCount = parseInt(order_list[i].querySelector('.market_listing_price').innerText.split('@')[0]);
                                    let orderGoodsRemainCount = parseInt(orderGoodsCount - (res_list[orderGoodsName] ? res_list[orderGoodsName] : 0));
                                    let tr = document.createElement('tr');
                                    // 累加一共有多少个
                                    total_count += parseInt(orderGoodsCount);
                                    // 累加一共有多少钱
                                    let tmpOrderGoodsPrice = orderGoodsPrice.replace(/[$\s]/g, '');
                                    console.log(tmpOrderGoodsPrice);
                                    total_price += convertToCents(tmpOrderGoodsPrice) * parseInt(orderGoodsCount);
                                    // 给tr添加字体颜色为red的样式
                                    if (orderGoodsRemainCount != orderGoodsCount) {
                                        tr.style.color = 'red';
                                    }
                                    // 设置表格的每一行数据
                                    tr.innerHTML = `
                                        <td class="orderID"><span>${orderID}</span></td>
                                        <td class="goodsName">${orderGoodsName}</td>
                                        <td class="orderGoodsPrice">${orderGoodsPrice}</td>
                                        <td class="orderGoodsCount">${orderGoodsCount}</td>
                                        <td class="orderGoodsRemainCount">${orderGoodsRemainCount}</td>
                                        <td class="ST-Link"><a href="https://steamcommunity.com/market/">ST-Link</a></td>
                                    `;
                                    tbody.appendChild(tr);
                                    // 为每一行的 orderID 添加点击事件
                                    let cancelOrderBtn = tr.querySelector('.orderID > span');
                                    cancelOrderBtn.addEventListener('click', function () {
                                        // 获取当前行的orderID
                                        let orderID = cancelOrderBtn.innerText;
                                        // 调用取消订购单的函数
                                        cancelOrder(orderID, () => {
                                            // 删除当前行
                                            tr.parentNode.removeChild(tr);
                                            // 顶部表示一共多少个以及多少钱的变量
                                            let total_count = 0;
                                            let total_price = 0;
                                            // 重新计算总数量和总价格
                                            let all_tr = box.querySelectorAll('.steamCommitedOrdersTbody > tr');
                                            for (let i = 0; i < all_tr.length; i++) {
                                                total_count += parseInt(all_tr[i].querySelector('.orderGoodsCount').innerText);
                                                let tmpOrderGoodsPrice = all_tr[i].querySelector('.orderGoodsPrice').innerText.replace(/[$\s]/g, '');
                                                total_price += convertToCents(tmpOrderGoodsPrice) * parseInt(all_tr[i].querySelector('.orderGoodsCount').innerText);
                                                // 显示总数量和总价格
                                                document.querySelector("body > div.select_steam_commited_orders_shadow > div > div.topline > span:nth-child(2) > span.steamCommitedOrderCount").innerText = total_count;
                                                document.querySelector("body > div.select_steam_commited_orders_shadow > div > div.topline > span:nth-child(2) > span.steamCommitedAllOrderPrice").innerText = convertToYuan(total_price);
                                            }
                                        });
                                    });
                                }
                                tbody.style.display = 'table-row-group';
                                // 显示总数量和总价格
                                document.querySelector("body > div.select_steam_commited_orders_shadow > div > div.topline > span:nth-child(2) > span.steamCommitedOrderCount").innerText = total_count;
                                document.querySelector("body > div.select_steam_commited_orders_shadow > div > div.topline > span:nth-child(2) > span.steamCommitedAllOrderPrice").innerText = convertToYuan(total_price);
                                box.querySelector('.loadingSteamCommitedOrdersTbody').style.display = 'none';
                            },
                            ontimeout: function () {
                                info("检测到steam连接性出错：尝试超时");
                                alert("获取历史订单数据失败，请更换网络环境并刷新浏览器");
                            }
                        });
                    }
                },
                ontimeout: function () {
                    info("检测到steam连接性出错：尝试超时");
                    alert("获取st订购单数据失败，请更换网络环境并刷新浏览器");
                }
            });
        }

        // 取消某一个订购单
        // delect_order is a callback function
        function cancelOrder(orderID, delect_order) {
            // 获取到sessionid
            GM_xmlhttpRequest({
                url: 'https://steamcommunity.com/market/',
                timeout: 20000,
                method: 'get',
                onload: function (res) {
                    if (res && res.status == 200) {
                        // 获取响应的html文档
                        let resText = res.responseText;
                        // 搜索响应体中出现的 g_sessionID
                        let g_sessionID = resText;
                        g_sessionID = g_sessionID.substring(g_sessionID.indexOf('g_sessionID'));
                        g_sessionID = g_sessionID.substring(g_sessionID.indexOf('\"') + 1);
                        g_sessionID = g_sessionID.substring(0, g_sessionID.indexOf('\"'));
                        // 调用取消订购单的函数
                        if (!delect_order) { delect_order = () => {} };
                        _cancelOrder(g_sessionID, orderID, delect_order);
                    } else {
                        console.log("检测到steam连接性出错：状态错误", res);
                        alert('检测到steam连接性出错, 取消订购单失败');
                    }
                },
                onerror: function (err) {
                    console.log("检测到steam连接性出错：连接错误", err);
                    alert('检测到steam连接性出错, 取消订购单失败');
                },
                ontimeout: function () {
                    console.log("检测到steam连接性出错：尝试超时");
                    alert('检测到steam连接超时, 取消订购单失败, 请更换网络环境');
                }
            });

            // 封装一个函数，用于取消订购单
            function _cancelOrder(sessionID, orderID, delect_order) {
                // 获取取消订购单的URL
                // https://steamcommunity.com/market/cancelbuyorder/sessionid=31a3b3f8b97bce37c90faef4&buy_orderid=7477586076
                let cancelOrderURL = `https://steamcommunity.com/market/cancelbuyorder/`;
                let params = `sessionid=${sessionID}&buy_orderid=${orderID}`;
                // 使用GM_xmlhttpRequest发送一个HTTP请求，用于取消订购单
                GM_xmlhttpRequest({
                    method: 'post',
                    url: cancelOrderURL,
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        "Referer": 'https://steamcommunity.com/market/',
                    },
                    data: params,
                    onload: function (res) {
                        info('【取消 st订购单 的返回结果】', res);
                        let response = JSON.parse(res.responseText);
                        if (response.success) {
                            // 删除对应订购单条目
                            if (!delect_order) { delect_order = () => {} };
                            delect_order();
                            // 弹窗提示
                            setTimeout(() => {
                                alert('取消订购单成功');
                            }, 1000);
                        } else {
                            alert('取消订购单失败，请检查网络并刷新后重试');
                        }
                    },
                    onerror: function (err) {
                        console.log("检测到steam连接性出错：连接错误", err);
                        alert('检测到steam连接性出错, 取消订购单失败');
                    },
                    ontimeout: function () {
                        console.log("检测到steam连接性出错：尝试超时");
                        alert('检测到steam连接超时, 取消订购单失败, 请更换网络环境');
                    }
                });
            }
        }

        // 将金额转换为单位分
        function convertToCents(amountStr) {
            // 使用parseFloat来解析字符串为浮点数，parseFloat会忽略字符串末尾的非数字字符
            let amount = parseFloat(amountStr);

            // 检查转换后的金额是否为NaN（不是一个数字），或者是否为无限大/无限小
            if (isNaN(amount) || !isFinite(amount)) {
                // 如果输入不是有效的数字，可以抛出一个错误或者返回一个特定的值
                throw new Error('Invalid amount: ' + amountStr);
            }

            // 将金额从元转换为分
            return Math.round(amount * 100);
        }

        // 将金额从整型形式的单位分转换为字符串形式的单位元
        function convertToYuan(cents) {
            // 确保cents是一个整数
            if (!Number.isInteger(cents)) {
                throw new Error('Amount must be an integer representing cents');
            }

            // 将单位分转换为元
            let yuan = cents / 100;

            // 使用toFixed方法格式化数字为字符串
            let formattedYuan = yuan.toFixed(2);

            // 返回格式化后的字符串
            return formattedYuan;
        }

        // 添加下单按钮的功能
        function add_create_order_btn() {
            let btn = document.querySelector("body > div.calc-profit-box > div:nth-child(8) > div > div:nth-child(2) > span");
            btn.addEventListener('click', function (e) {
                if (location.pathname.startsWith("/goods/")) {
                    // 市场详情页可以下单
                    // 获取商品名称
                    let good_name = document.querySelector("body > div.market-list > div > div.detail-header.black > div.detail-cont > div:nth-child(1) > h1").innerText;
                    // 获取跳转到steam的链接
                    let stLink = document.querySelector("body > div.market-list > div > div.detail-header.black > div.detail-cont > div:nth-child(1) > a");
                    let stLinkHref = stLink.getAttribute('href');
                    let market_hash_name = stLinkHref.substring(stLinkHref.indexOf('730/') + 4);
                    market_hash_name = market_hash_name.substring(0, market_hash_name.indexOf('?'));
                    market_hash_name = decodeURIComponent(market_hash_name);  // Nova%20%7C%20Windblown%20%28Minimal%20Wear%29
                    market_hash_name = market_hash_name.replace(/ /g, '+');
                    market_hash_name = market_hash_name.replace('|', '%7C');
                                                                              // Nova+%7C+Windblown+(Minimal+Wear)
                    // 获取到该商品的steam求购价
                    let steamBuyPrice = document.getElementById("buymoney").value;
                    steamBuyPrice = convertToCents(steamBuyPrice);
                    // 获取到购买数量
                    // let quantity = 20;
                    let quantity = parseInt(document.querySelector("#input_buyCount").value);
                    // 计算购买总价
                    let totalPrice = steamBuyPrice * quantity;
                    // 获取到sessionid
                    GM_xmlhttpRequest({
                        url: stLinkHref,
                        timeout: 5000,
                        method: 'get',
                        onload: function (res) {
                            if (res && res.status == 200) {
                                // 获取响应的html文档
                                let resText = res.responseText;
                                // 搜索响应体中出现的 g_sessionID
                                let g_sessionID = resText;
                                g_sessionID = g_sessionID.substring(g_sessionID.indexOf('g_sessionID'));
                                g_sessionID = g_sessionID.substring(g_sessionID.indexOf('\"') + 1);
                                g_sessionID = g_sessionID.substring(0, g_sessionID.indexOf('\"'));
                                // 从 localStorage 中获取 账单地址
                                let zhangdandizhi = localStorage.getItem("zhangdandizhi") ? JSON.parse(localStorage.getItem("zhangdandizhi")): {
                                    name: "",
                                    first_name: "",
                                    address1: "",
                                    address2: "",
                                    city: "",
                                    sheng: "AK",
                                    youzhengcode: ""
                                };
                                // 获取下单所需要的数据
                                let data = [
                                    ['sessionid', g_sessionID],
                                    ['currency', 1],
                                    ['appid', 730],
                                    ['market_hash_name', market_hash_name],
                                    ['price_total', totalPrice],                               // 价格以分为单位的整型
                                    ['quantity', quantity],                                    // 购买数量
                                    ['first_name', zhangdandizhi.name],                        // 名
                                    ['last_name', zhangdandizhi.first_name],                   // 姓
                                    ['billing_address', zhangdandizhi.address1],               // 账单地址1
                                    ['billing_address_two', zhangdandizhi.address2],           // 账单地址2
                                    ['billing_country', 'US'],                                 // 国家
                                    ['billing_city', zhangdandizhi.city],                      // 城市
                                    ['billing_state', zhangdandizhi.sheng],                    // 省
                                    ['billing_postal_code', zhangdandizhi.youzhengcode],       // 邮编
                                    ['save_my_address', 1]
                                ];
                                // 将data拼接为表单字符串
                                let dataStr = "";
                                for (let i = 0; i < data.length; i++) {
                                    dataStr += data[i][0] + "=" + data[i][1];
                                    if (i != data.length - 1) {
                                        dataStr += "&";
                                    }
                                }
                                // "sessionid=c4966afc0cc7a1d4a3a83e0a&currency=1&appid=730&market_hash_name=Nova+%7C+Windblown+(Minimal+Wear)&price_total=5&quantity=1&first_name=xiaoyang&last_name=liu&billing_address=zixingtianxiedezhangdandizhi1&billing_address_two=zixingtianxiedezhangdandizhi2&billing_country=US&billing_city=chengshi2&billing_state=AK&billing_postal_code=90230&save_my_address=1";
                                // 将本商品加入选品库
                                // ---- 记录下单所需的所有值
                                // 发送请求到steam完成下单
                                GM_xmlhttpRequest({
                                    url: "https://steamcommunity.com/market/createbuyorder/",
                                    timeout: 5000,
                                    method: 'post',
                                    headers: {
                                        "host": 'steamcommunity.com',
                                        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                                        "Referer": stLinkHref,
                                        "Origin": "https://steamcommunity.com",
                                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"
                                    },
                                    data: dataStr,
                                    onload: function (res) {
                                        if (res && res.status == 200) {
                                            let resText = res.responseText;
                                            let resJSON = JSON.parse(resText);
                                            if (resJSON.success == 1) {
                                                // 需要保存到选品库的数据有：商品哈希名称、价格、数量、stLink
                                                let data = {
                                                    good_name: good_name,
                                                    market_hash_name: market_hash_name,
                                                    price: convertToYuan(steamBuyPrice),
                                                    quantity: quantity,
                                                    stLink: stLinkHref
                                                };
                                                let xuanpingku = localStorage.getItem("xuanpingku") ? JSON.parse(localStorage.getItem("xuanpingku")) : [];
                                                xuanpingku.push(data);
                                                localStorage.setItem("xuanpingku", JSON.stringify(xuanpingku));
                                                alert("下单成功，已将本商加入选品库，请到选品库查看");
                                            } else {
                                                info(res);
                                                info(data);
                                                alert("下单失败！"+JSON.parse(res.responseText).message);
                                            }
                                        } else {
                                            console.log("检测到steam连接性出错：状态错误", res);
                                            info(res);
                                            info(data);
                                            alert('下单失败');
                                        }
                                    },
                                    onerror: function (err) {
                                        console.log("检测到steam连接性出错：连接错误", err);
                                        alert('检测到steam连接性出错, 下单失败');
                                    },
                                    ontimeout: function () {
                                        console.log("检测到steam连接性出错：尝试超时");
                                        alert('检测到steam连接性出错, 下单失败');
                                    }
                                });
                            } else {
                                console.log("检测到steam连接性出错：状态错误", res);
                                alert('检测到steam连接性出错, 下单失败');
                            }
                        },
                        onerror: function (err) {
                            console.log("检测到steam连接性出错：连接错误", err);
                            alert('检测到steam连接性出错, 下单失败');
                        },
                        ontimeout: function () {
                            console.log("检测到steam连接性出错：尝试超时");
                            alert('检测到steam连接超时, 下单失败, 请更换网络环境');
                        }
                    });
                } else if (location.pathname.startsWith("/market/")) {
                    // 市场列表页不可以下单
                    alert("当前页面不可以下单");
                }
            });
        }

        // 获取 steam 的 session_id
        async function get_session_id(stLinkHref) {
            let session_id = await new Promise((resolve, reject) => {
                GM_xmlhttpRequest({
                    url: stLinkHref,
                    timeout: 5000,
                    method: 'get',
                    onload: function (res) {
                        if (res && res.status == 200) {
                            // 获取响应的html文档
                            let resText = res.responseText;
                            // 搜索响应体中出现的 g_sessionID
                            let g_sessionID = resText;
                            g_sessionID = g_sessionID.substring(g_sessionID.indexOf('g_sessionID'));
                            g_sessionID = g_sessionID.substring(g_sessionID.indexOf('\"') + 1);
                            g_sessionID = g_sessionID.substring(0, g_sessionID.indexOf('\"'));
                            resolve(g_sessionID);
                        } else {
                            console.log("检测到steam连接性出错：状态错误", res);
                            alert('检测到steam连接性出错, 下单失败');
                            resolve(null);
                        }
                    },
                    onerror: function (err) {
                        console.log("检测到steam连接性出错：连接错误", err);
                        alert('检测到steam连接性出错, 下单失败');
                        resolve(null);
                    },
                    ontimeout: function () {
                        console.log("检测到steam连接性出错：尝试超时");
                        alert('检测到steam连接超时, 下单失败, 请更换网络环境');
                        resolve(null);
                    }
                })
            });
            return session_id;
        }

        // 下单一件商品
        async function buy_item(g_sessionID, market_hash_name, totalPrice, quantity, stLinkHref) {
            // 从 localStorage 中获取 账单地址
            let zhangdandizhi = localStorage.getItem("zhangdandizhi") ? JSON.parse(localStorage.getItem("zhangdandizhi")): {
                name: "",
                first_name: "",
                address1: "",
                address2: "",
                city: "",
                sheng: "AK",
                youzhengcode: ""
            };
            // 获取下单所需要的数据
            let data = [
                ['sessionid', g_sessionID],
                ['currency', 1],
                ['appid', 730],
                ['market_hash_name', market_hash_name],
                ['price_total', totalPrice],                               // 价格以分为单位的整型
                ['quantity', quantity],                                    // 购买数量
                ['first_name', zhangdandizhi.name],                        // 名
                ['last_name', zhangdandizhi.first_name],                   // 姓
                ['billing_address', zhangdandizhi.address1],               // 账单地址1
                ['billing_address_two', zhangdandizhi.address2],           // 账单地址2
                ['billing_country', 'US'],                                 // 国家
                ['billing_city', zhangdandizhi.city],                      // 城市
                ['billing_state', zhangdandizhi.sheng],                    // 省
                ['billing_postal_code', zhangdandizhi.youzhengcode],       // 邮编
                ['save_my_address', 1]
            ];
            // 将data拼接为表单字符串
            let dataStr = "";
            for (let i = 0; i < data.length; i++) {
                dataStr += data[i][0] + "=" + data[i][1];
                if (i != data.length - 1) {
                    dataStr += "&";
                }
            }
            return await new Promise((resolve, reject) => {
                GM_xmlhttpRequest({
                    url: "https://steamcommunity.com/market/createbuyorder/",
                    timeout: 5000,
                    method: 'post',
                    headers: {
                        "host": 'steamcommunity.com',
                        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                        "Referer": stLinkHref,
                        "Origin": "https://steamcommunity.com",
                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"
                    },
                    data: dataStr,
                    onload: function (res) {
                        if (res && res.status == 200) {
                            let resText = res.responseText;
                            let resJSON = JSON.parse(resText);
                            if (resJSON.success == 1) {
                                // 返回下单成功
                                resolve(true);
                            } else {
                                info(res);
                                info(data);
                                alert("下单失败！"+JSON.parse(res.responseText).message);
                                resolve(null);
                            }
                        } else {
                            console.log("检测到steam连接性出错：状态错误", res);
                            info(res);
                            info(data);
                            alert('下单失败');
                            resolve(null);
                        }
                    },
                    onerror: function (err) {
                        console.log("检测到steam连接性出错：连接错误", err);
                        alert('检测到steam连接性出错, 下单失败');
                        resolve(null);
                    },
                    ontimeout: function () {
                        console.log("检测到steam连接性出错：尝试超时");
                        alert('检测到steam连接性出错, 下单失败');
                        resolve(null);
                    }
                });
            });
        }

        // 添加查看选品库功能
        function add_check_item_library_btn() {
            let btn = document.querySelector("body > div.calc-profit-box > div:nth-child(4) > div > div:nth-child(2) > span");
            btn.innerText = "查看选品库";
            let box_shadow = document.querySelector('.check_item_library_shadow');
            let box = document.querySelector('.check_item_library');

            // 添加点击事件
            btn.addEventListener('click', function (e) {
                if (box_shadow.style.display == 'block') {
                    box_shadow.style.display = 'none';
                } else {
                    // 更新选品库的内容
                    //     读取 localstorage 的内容
                    let xuanpingku = localStorage.getItem("xuanpingku") ? JSON.parse(localStorage.getItem("xuanpingku")) : [];
                    // 渲染到页面上 并 更新每一行的删除按钮功能
                    show_xuanpingku(xuanpingku);
                    // 显示选品库界面
                    box_shadow.style.display = 'block';
                }
            });

            // 隐藏界面的事件
            box_shadow.addEventListener('click', function (e) {
                box_shadow.style.display = 'none';
            });

            // 操作界面时阻止界面被隐藏
            box.addEventListener('click', function (e) {
                e.stopPropagation();
            });

            // 选品库 下单所有选品 按钮 的 功能
            let buyAllItemBtn = document.querySelector('.check_item_library_shadow .buyAllItemBtn');
            buyAllItemBtn.addEventListener('click', async function (e) {
                // 获取本地存储数据
                let xuanpingku = localStorage.getItem("xuanpingku") ? JSON.parse(localStorage.getItem("xuanpingku")) : [];
                // 获取选品库中所有行
                let xuanpingku_row = document.querySelectorAll('.check_item_library_shadow .table-box tbody tr');
                // 遍历数据 并 下单
                for (let i = 0; i < xuanpingku.length; i++) {
                    // 获取数据
                    // let good_name = xuanpingku[i].good_name;
                    let stLinkHref = xuanpingku[i].stLink;                   // 下单的steam链接
                    let market_hash_name = xuanpingku[i].market_hash_name;   // 下单使用的hash名称
                    let price = xuanpingku[i].quantity;                      // 下单的数量
                    let quantity = convertToCents(xuanpingku[i].price);      // 求购的价格
                    let totalPrice = price * quantity;                       // 总价格
                    // 获取 session_id
                    let session_id = await get_session_id(stLinkHref);
                    if (!session_id) {
                        break;
                    }
                    // 下单操作
                    let result = await buy_item(session_id, market_hash_name, totalPrice, price, stLinkHref);
                    if (!result) {
                        xuanpingku_row[i].querySelector('.buy_status').innerHTML = `<span style="color: red">下单失败</span>`;
                        break;
                    }
                    // 修改状态文字
                    xuanpingku_row[i].querySelector('.buy_status').innerHTML = `<span style="color: rgb(72,139,72)">下单成功</span>`;
                }
            });
            
            // 选品库 删除所有选品 按钮 的 功能
            let deleteAllItemBtn = document.querySelector('.check_item_library_shadow .deleteAllItemBtn');
            deleteAllItemBtn.addEventListener('click', function (e) {
                // 删除本地存储数据
                localStorage.setItem("xuanpingku", "[]");
                // 删除选品页面中所有数据
                document.querySelector('.check_item_library_shadow .table-box tbody').innerHTML = '';
            });

            // 选品库 导出选品库 按钮 的 功能
            let outputAllItemBtn = document.querySelector('.check_item_library_shadow .outputAllItemBtn');
            outputAllItemBtn.addEventListener('click', function (e) {
                // 获取本地存储数据
                let xuanpingku = localStorage.getItem("xuanpingku") ? JSON.parse(localStorage.getItem("xuanpingku")) : [];
                // 导出为 json 文件
                let blob = new Blob([JSON.stringify(xuanpingku)], { type: 'application/json' });
                let url = URL.createObjectURL(blob);
                let link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', '选品库.json');
                link.click();
                URL.revokeObjectURL(url);
            });

            // 选品库 导入选品库 按钮 的 功能
            let importAllItemBtn = document.querySelector('.check_item_library_shadow .importAllItemBtn');
            importAllItemBtn.addEventListener('click', function (e) {
                // 创建文件输入标签
                const fileInputEle = document.createElement('input');
                fileInputEle.type = 'file';
                fileInputEle.addEventListener('change', function (e) {
                    const file = e.target.files[0];
                    const reader = new FileReader();
                    // 读取成功之后执行以下函数
                    reader.onload = function (e) {
                        // 转为json格式方便展示
                        const json = JSON.parse(e.target.result);
                        // 存储到本地存储
                        localStorage.setItem("xuanpingku", JSON.stringify(json));
                        // 渲染到页面上 并 更新每一行的删除按钮功能
                        show_xuanpingku(json);
                    }
                    // 读取文件
                    reader.readAsText(file);
                });
                // 点击标签进行文件选择
                fileInputEle.click();
            });

            info('【set btn】查看查看选品库界面按钮');
        }

        // 将json数据渲染到页面中 并 更新每一行的删除按钮功能
        function show_xuanpingku(json) {
            let xuanpingku_html = '';
            for (let i = 0; i < json.length; i++) {
                let item = json[i];
                let item_html = `
                    <tr>
                        <td class="item_name">${item.good_name}</td>
                        <td class="item_price">${item.price}</td>
                        <td class="item_quantity">${item.quantity}</td>
                        <td class="item_stLink"><a href="${item.stLink}" target="_blank">steam链接</a></td>
                        <td class="buy_status">未购买</td>
                        <td class="item_del_col"><button class="del_btn" key="${i+1}">删除</button></td>
                    </tr>
                `;
                xuanpingku_html += item_html;
            }
            document.querySelector('.check_item_library_shadow .table-box tbody').innerHTML = xuanpingku_html;
            // 更新选品库每一行的删除按钮事件
            update_xuanpingku_DelBtn();
        }

        // 更新选品库每一行的删除按钮事件
        function update_xuanpingku_DelBtn() {
            function updareDelBtn(e) {
                console.log(e.target);
                // 获取当前行的key值
                let key = parseInt(e.target.getAttribute('key')) - 1;
                // 获取当前选品库里的所有商品
                let xuanpingku = localStorage.getItem("xuanpingku") ? JSON.parse(localStorage.getItem("xuanpingku")) : [];
                if (xuanpingku.length > 0) {
                    // 删除当前行
                    xuanpingku.splice(key, 1);
                    // 更新本地存储
                    localStorage.setItem("xuanpingku", JSON.stringify(xuanpingku));
                    // 重新渲染选品库列表到页面中
                    show_xuanpingku(xuanpingku);
                }
            }
            let del_btn_list = document.querySelectorAll('.check_item_library_shadow .table-box tbody .del_btn');
            for (let i = 0; i < del_btn_list.length; i++) {
                del_btn_list[i].addEventListener('click', updareDelBtn);
            }
        }
    })();
})();
